r - Addining row number of sub dataframe -
i have following dataframe:
> df1 var1 var2 var3 1 ac bc bc 2 bc bc cc 3 dc ec dc 4 gc gc gc
i have sub dataframe above df1 (only 2 rows remained of 4):
> df2 var1 var2 var3 2 bc bc cc 3 dc ec dc
i numbers of df2 r (r = 2,3
). in addition add df1 new column indicate 1 row exists in df2. in final df1 following:
> df1 var1 var2 var3 df2 1 ac bc bc 0 2 bc bc cc 1 3 dc ec dc 1 4 gc gc gc 0
how can it?
we can use %in%
to compare rownames of 'df1' , 'df2'. logical vector can coerced binary format wrapping +
.
df1$newcol <- +(rownames(df1) %in% rownames(df2)) df1 # var1 var2 var3 newcol #1 ac bc bc 0 #2 bc bc cc 1 #3 dc ec dc 1 #4 gc gc gc 0
if need row names common, use intersect
intersect(rownames(df1), rownames(df2)) #[1] "2" "3"
Comments
Post a Comment