根据另一变量将值从一列复制到其他多个列

时间:2018-10-17 08:35:25

标签: r

我想将值从一列复制到新变量,然后根据条件将此值添加到其他列。

最小的例子是

VP <- c("1","1","2","1","1","2","2","1", "1")
Group <- c("1","1","1","2","2","2","3","3", "3")
Value<-c("6","4","7","2","3","8","4","3", "5")

df <- data.frame(cbind(VP, Group, Value))

目标将是这样的结果:

      VP Group Value NewVariable
      1     1     6     7
      1     1     4     7
      2     1     7
      1     2     2     8
      1     2     3     8
      2     2     8
      2     3     4
      1     3     3     4
      1     3     5     4

因此,取VP的值,并将其复制到相应组中的每个其他人(除了自己的行之外)。

2 个答案:

答案 0 :(得分:1)

一种可能的方法是更新联接

library(data.table)
setDT(df)[df[VP == "2"][, VP := "1"], on = .(VP, Group), NewVariable := i.Value]
df
   VP Group Value NewVariable
1:  1     1     6           7
2:  1     1     4           7
3:  2     1     7        <NA>
4:  1     2     2           8
5:  1     2     3           8
6:  2     2     8        <NA>
7:  2     3     4        <NA>
8:  1     3     3           4
9:  1     3     5           4

或者,将NA替换为:

setDT(df)[df[VP == "2"][, VP := "1"], on = .(VP, Group), NewVariable := i.Value][
  is.na(NewVariable), NewVariable := ""]
df
   VP Group Value NewVariable
1:  1     1     6           7
2:  1     1     4           7
3:  2     1     7            
4:  1     2     2           8
5:  1     2     3           8
6:  2     2     8            
7:  2     3     4            
8:  1     3     3           4
9:  1     3     5           4

答案 1 :(得分:1)

假设我们每能做的一组VP = 2都有一个值

library(dplyr)
df %>%
  group_by(Group) %>%
  mutate(NewVar = ifelse(VP == 2, NA, Value[VP == 2]))


#  VP    Group Value NewVar
#  <chr> <chr> <chr> <chr> 
#1 1     1     6     7     
#2 1     1     4     7     
#3 2     1     7     NA    
#4 1     2     2     8     
#5 1     2     3     8     
#6 2     2     8     NA    
#7 2     3     4     NA    
#8 1     3     3     4     
#9 1     3     5     4     

我在这里返回NA而不是空字符串。您可以根据自己的喜好进行选择。

数据

VP <- c("1","1","2","1","1","2","2","1", "1")
Group <- c("1","1","1","2","2","2","3","3", "3")
Value<-c("6","4","7","2","3","8","4","3", "5")
df <- data.frame(VP, Group, Value, stringsAsFactors = FALSE)