我不知道从哪里开始使用这段代码.我想将一个新变量附加到现有数据框架,该数据框架根据分组变量采用不同的列.例如,假设我有列
A B C D E F
1 2 3 6 11 12
1 7 5 10 8 9
2 19 2 4 5 6
2 8 4 3 1 1
Run Code Online (Sandbox Code Playgroud)
我想附加一个新列"G",如果A是1则是B列,如果A是2,则是D列
A B C D E F G
1 2 3 6 11 12 2
1 7 5 10 8 9 7
2 19 2 4 5 6 4
2 8 4 3 1 1 3
Run Code Online (Sandbox Code Playgroud)
谢谢
这里有几个选项.
假设您的data.frame被调用 DF
[和索引# make everything in G = B
DF$G <- DF$B
# replace those cases where A==2 with D
DF$G[DF$A==2] <- DF$D[DT$A==2]
Run Code Online (Sandbox Code Playgroud)
只ifelse需要一个语句,因为A是1或2
DF$G <- ifelse(DF$A==2, DF$D, DF$B)
Run Code Online (Sandbox Code Playgroud)
我喜欢data.table,用于内存效率和编码优雅
library(data.table)
# create a data.table with A as the key
DT <- data.table(DF, key = 'A')
# where the key (A) == 1 ], then assign G = B
DT[.(1), G := B]
# and where the key (A) == 2, then assign G = D
DT[.(2), G := D]
Run Code Online (Sandbox Code Playgroud)
精美优雅!
假设你data.frame被称为"mydf",你可以使用ifelse:
within(mydf, {
G <- ifelse(A == 1, B,
ifelse(A == 2, D,
0))
})
# A B C D E F G
# 1 1 2 3 6 11 12 2
# 2 1 7 5 10 8 9 7
# 3 2 19 2 4 5 6 4
# 4 2 8 4 3 1 1 3
Run Code Online (Sandbox Code Playgroud)