简体   繁体   English

如何使用dplyr根据另一列的不同值在新列中填充不同的值?

[英]How to fill different values in a new column based on different values of another column using dplyr?

Here is my data: 这是我的数据:

a <- data.frame(x=c('A','A','A','B','B','B'),
                y=c('Yes','No','No','Yes','No','No'),
                z=c(1,2,3,4,5,6))

I want to generate a new column this way: 我想以这种方式生成一个新列:

  1. Group by x , so all the A s will be in one group and all B s in another x分组,因此所有A都在一个组中,所有B在另一个组中
  2. For every group, if y=Yes , then keep the z value in the new column. 对于每个组,如果y=Yes ,则将z值保留在新列中。 If y=No , then using the z value with y=Yes . 如果y=No ,则将z值与y=Yes

So, the new data should look like this: 因此,新数据应如下所示:

x    y   z   z1
A   Yes  1   1
A   No   2   1
A   No   3   1
B   Yes  4   4
B   No   5   4
B   No   6   4

I can use this way to do: 我可以用这种方式来做:

a1 <- a %>%
   filter(y=='Yes') %>%
   distinct(x,y,z)
 a2 <- a %>%
    left_join(a1,by='x') %>%...

But in this way, I have to generate a1 as an intermediate. 但是以这种方式,我必须生成a1作为中间体。 How to do this just in one pipeline without generating a new variable like a1 in my example? 在我的示例中,如何仅在一个管道中执行此操作而不生成像a1这样的新变量?

You could combine both pipelines and perform the same functions in one shot. 您可以将两个管道结合在一起,一次执行相同的功能。

ie.. 即..

    a <- data.frame(x=c('A','A','A','B','B','B'),
                    y=c('Yes','No','No','Yes','No','No'),
                    z=c(1,2,3,4,5,6))

    a %>% left_join(a %>% filter(y=='Yes') %>% distinct(x,y,z), by='x') %>% select(-y.y)

This results in duplicate columns tagged with .x and .y as a result of the join. 作为连接的结果,这将导致使用.x和.y标记的重复列。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用dplyr根据另一列中的值添加新列 - adding a new column based upon values in another column using dplyr R:如何使用另一列的值填充新列中的值 - R: How to fill in values in a new column using the values of another column 使用 dplyr 根据来自另一列的值的总和创建一个新列 - Create a new column based on the sum of values from another column, with dplyr 在 dplyr package 中,您可以根据不同列中的值改变列 - In the dplyr package can you mutate a column based on the values in a different column 使用Dplyr使用另一列中的相应值填充空白单元格 - Using Dplyr fill empty cells using corresponding values in another column 有没有办法在 R 中使用 dplyr 根据另一个列的值创建一个新列? - Is there a way to create a new column based on the values of another one using dplyr in R? 如何使用dplyr根据另一列中的字符值的一部分更新列值? - how to renew column values based on part of character value in another column using dplyr? r、dplyr:如何使用 gsub 根据另一列中的值转换一列中的值 - r, dplyr: how to transform values in one column based on value in another column using gsub 如何使用另一列中的值和条件填充列 - How to fill a column based with values and conditions from another column 根据值在其他列中出现的频率,用不同的数字填充新列,R - Fill new column with different numbers depending on how often values appear in other column, R
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM