将 2 个变量重新编码为一行中的一个
Recode 2 variables to one in one line
假设我有一个像这样的 DF:
df=data.frame(a=c(0,0,1,1),b=c(0,1,0,1))
只有它有一个长号。的行。我想根据 a 和 b 的同时值创建一个列,例如
df
a b c
0 0 10
0 1 11
1 0 12
1 1 13
我认为这可以通过内部连接来完成,使用 sqldf 或者 dplyr;有没有图书馆有更快的方法吗?
提前致谢,p
你可以这样做:
library(dplyr)
df %>% mutate(newcol = paste0(a, b))
取决于您希望如何标记新列。
如果您有所需值的向量,我们将其称为查找:
lookup <- 10:100
df %>% mutate(newcol = lookup[as.factor(paste0(a, b))])
超级作弊,仅适用于此示例但是:
df$c <- 10 + df$b + df$a*2
?
否则,看 ?merge
我认为你的意思是你有一些其他的数据框(比如叫做dictionary
)有一个c
列,然后你查找字典中的 (a, b) 并从那里获取 c
??
df=data.frame(a=c(0,0,1,1),b=c(0,1,0,1))
dictionary <- df
dictionary$c <- 10:13
dictionary <- dictionary[sample(4), ] # shuffle it just to prove it works
那样的话你可以做
merge(df, dictionary, merge=c('a', 'b'), all.x=T)
这将从 dictionary
中获取匹配的 c
列并将其插入 df
。如果 dictionary
.
中没有匹配的 (a, b),all.x
将在其中放置一个 NA
如果速度成为问题,您可以尝试 data.table
library(data.table)
setDT(df) # convert to data.table
setDT(dictionary) # convert to data.table
# set key
setkey(df,a,b)
setkey(dictionary,a,b)
# merge
dictionary[df] # will be `df` with the `c` column added, `NA` if no match
假设我有一个像这样的 DF:
df=data.frame(a=c(0,0,1,1),b=c(0,1,0,1))
只有它有一个长号。的行。我想根据 a 和 b 的同时值创建一个列,例如
df
a b c
0 0 10
0 1 11
1 0 12
1 1 13
我认为这可以通过内部连接来完成,使用 sqldf 或者 dplyr;有没有图书馆有更快的方法吗?
提前致谢,p
你可以这样做:
library(dplyr)
df %>% mutate(newcol = paste0(a, b))
取决于您希望如何标记新列。
如果您有所需值的向量,我们将其称为查找:
lookup <- 10:100
df %>% mutate(newcol = lookup[as.factor(paste0(a, b))])
超级作弊,仅适用于此示例但是:
df$c <- 10 + df$b + df$a*2
?
否则,看 ?merge
我认为你的意思是你有一些其他的数据框(比如叫做dictionary
)有一个c
列,然后你查找字典中的 (a, b) 并从那里获取 c
??
df=data.frame(a=c(0,0,1,1),b=c(0,1,0,1))
dictionary <- df
dictionary$c <- 10:13
dictionary <- dictionary[sample(4), ] # shuffle it just to prove it works
那样的话你可以做
merge(df, dictionary, merge=c('a', 'b'), all.x=T)
这将从 dictionary
中获取匹配的 c
列并将其插入 df
。如果 dictionary
.
all.x
将在其中放置一个 NA
如果速度成为问题,您可以尝试 data.table
library(data.table)
setDT(df) # convert to data.table
setDT(dictionary) # convert to data.table
# set key
setkey(df,a,b)
setkey(dictionary,a,b)
# merge
dictionary[df] # will be `df` with the `c` column added, `NA` if no match