簡體   English   中英

使用基於其他列的變量“名稱”的值在 R 中添加列

[英]Add column in R with values based on variable 'names' of other columns

如果我們有一個 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)

感謝您的支持:)

我們可以在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)) 

附加選項

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM