[英]Adding values from one column to another with missing values in the second column using R
I want to add just some specific values from column z
in dataframe df2
into dataframe df1
, but just for the id = 1 and id = 3. 我只想将数据帧
df2
z
列中的某些特定值添加到数据帧df1
,但仅用于id = 1和id = 3。
I have already tried solutions with ifelse
, but for the missing values that kind of solutions work for the first value, until find the first missing gap. 我已经使用
ifelse
尝试了解决方案,但是对于缺少的值,那种解决方案适用于第一个值,直到找到第一个缺少的缺口。
df1$z <- ifelse((df1$id == df2$id), df2$z, 0)
Examples of the data: 数据示例:
df1 <- read.table(text = "
id v w
1 20 B
3 30 T
", h = T)
df2 <- read.table(text = "
id z b c d e f g h i j
1 100 z w e r y w u y q
2 800 t q j n m q i x z
3 700 f e q b a i e p w
4 300 a b c d a g s y q"
, h = T)
Expected result: 预期结果:
df1_add <- read.table(text = "
id v w z
1 20 B 100
3 30 T 700
", h = T)
Let's use left_join()
and select()
from the dplyr
package: 让我们使用
dplyr
包中的left_join()
和select()
:
library(dplyr)
df1_add <- df1 %>%
left_join(df2 %>% select(id, z))
df1_add
id v w z
1 1 20 B 100
2 3 30 T 700
you can try this 你可以试试这个
df_add <- df1
df_add$z = df2[df2$id %in% c(1, 3), ]$z
我们可以使用来自base R
merge
merge(df1, df2[c("id", "z")])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.