【问题标题】:Add column in R with values based on variable 'names' of other columns在 R 中添加列,其值基于其他列的变量“名称”
【发布时间】:2020-07-04 04:52:25
【问题描述】:

如果我们有一个 data.frame ,请说类似

    ///// !col1!col2!col3
      ---------------
id123   1    0    0
      ---------------
!id435   0    1    0
      ---------------
!id777   0    0    1

我想创建一个新列 newcol,其中变量名称的值具有 '1'

需要数据

    ///// !col1!col2!col3!newcol
      ---------------------
id123   1    0    0   !col1
      ---------------------
!id435   0    1    0  !col2
      ---------------------
!id777   0    0    1  !col3

1) 有没有办法在 base 或 plyr 中做? 2)(可选)如果 id123 在 col1 和 col2 中都有值 1 ,如何调整它?如何“添加”这些值,在 newcol 中用逗号分隔

temp$col1 <- c(1,0,0)
temp$col2 <- c(0,1,0)
temp$col3 <- c(0,0,1)

temp<-data.frame(temp$col1, temp$col2, temp$col3)

感谢您的支持 :)

【问题讨论】:

    标签: r dataframe dplyr tidyverse plyr


    【解决方案1】:

    我们可以在base R中使用max.col

    temp$newcol <- names(temp)[max.col(temp, 'first')]
    

    如果我们在同一行有多个 1,并且所有列名称为单个字符串

    i1 <- which(temp2 ==1, arr.ind = TRUE)
    temp2$newcol <- NA_character_
    temp2$newcol[unique(i1[,1])] <-  tapply(names(temp2)[i1[,2]],
             i1[,1], FUN = toString)
    temp2$newcol
    #[1] "col1"       "col1, col2" "col3"     
    

    这也将确保只分配给有 1 的行

    数据

    temp <- data.frame(col1  = c(1, 0, 0), col2 = c(0, 1, 0), col3 = c(0, 0, 1))
    temp2 <- data.frame(col1 = c(1, 1, 0), col2 = c(0, 1, 0), col3 = c(0, 0, 1)) 
    

    【讨论】:

    • 嗨 Akrun !!!,感谢您的快速响应,第二点呢,如果同一行有两个 1,上面的代码给出:只有第一列名称......如果我们这样做,如何在逗号后添加下一个? : temp
    【解决方案2】:

    附加选项

    library(tidyverse)
    temp2 <- data.frame(col1 = c(1, 1, 0), col2 = c(0, 1, 0), col3 = c(0, 0, 1)) 
    
    temp2 <- temp2 %>% 
      mutate(id = row_number())
    
    temp2 %>% 
      pivot_longer(-id) %>% 
      filter(value == 1) %>% 
      group_by(id) %>% 
      summarise(col = str_c(name, collapse = ", ")) %>% 
      left_join(temp2) %>% 
      select(-id)
    

    【讨论】:

    • 感谢 Yuriy,使用忍术的方法也不错 :)
    • 再次,Yuriy,实际数据出了点问题...,下面的代码有效,但计算出错误的数据,可能存在数据问题...var1 没有通用类型 > 和 var2 。 ..
    • 你能举一个接近真实数据结构的数据例子吗?我会尽力提供帮助。或者@akrun 的例子对你有帮助?
    • 我使用了这个解决方案,dt$di 0))))。但是如果连续有很多 1,我没有找到在 newcol 中添加逗号的方法......,其他代码给出错误
    • 不工作是指我拥有的数据,它与示例代码配合得很好 akrun 的第一个代码 = 不工作 第二个代码 akrun = 工作但结果错误(有 1,0和 NA 在我的数据中..) 也许您可以检查我提供的代码来调整它以识别行中是否存在多个 1.. ?您的代码不起作用,也许有办法向您发送迷你 cvs 数据。 (7 行)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多