简体   繁体   English

使用R将一列中的值添加到第二列中缺少值的另一列

[英]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.

相关问题 R - 基于使用另一列的函数为一列添加值 - R - adding values for one column based on a function using another column 将一列中的值添加到另一列中的值 - Adding values from one column to values in another 用于将一列中的值替换为另一列中的缺失值的R代码 - R code for substituting values from one column to the missing values in another column 如何在 R 中从第二行开始将值从一列复制到另一列 - How can I copy values from one column to another starting on the second row, in R 根据r中的ID从一列中查找另一列中的值 - Find values from one column in another column according to ID in r 使用另一列中的值填写数据集中的缺失值 - Fill in missing values in dataset using values from another column R 中,如何向数据集添加一列,该数据集从一列中添加值并从另一列中减去值? - How to add a column to a dataset which adds values from one column and subtracts values from another column in R? 在 R 中添加一个包含 tibble 特定列的缺失值的列 - Adding a column that contain te missing values of an specific column of a tibble in R 用 R dplyr 中另一列的值替换一列的值 - Replace the values of one column with values of another column in R dplyr R:提取一列中的唯一值与另一列中的值匹配 - R: Extract unique values in one column match by values in another column
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM