我正在尝试使用另一个对应的元素映射/替换一个数据帧的元素。让我举一个例子。
我有这个数据框:
rbind(c("a","b","c"),c("b","a","c"),c("c","b","a"))
[,1] [,2] [,3]
[1,] "a" "b" "c"
[2,] "b" "a" "c"
[3,] "c" "b" "a"
这一个:
rbind(c("a",1),c("b",2),c("c",3))
[,1] [,2]
[1,] "a" "1"
[2,] "b" "2"
[3,] "c" "3"
我怎样才能用1代替所有a,用2代替所有b,用3代替所有c。获得看起来像这样的最终数据框架。
1 2 3
2 1 3
3 2 1
另外,要了解我使用更大的数据集进行此操作。我似乎无法找到正确的方法来做到这一点。
提前谢谢!
答案 0 :(得分:3)
创建命名向量会更有意义。然后你可以使用" ["功能:
a <- rbind(c("a","b","c"),c("b","a","c"),c("c","b","a"))
b <- c("a"=1,"b"=2, "c"=3)
> b
a b c
1 2 3
> a[] <- b[a]
> a
[,1] [,2] [,3]
[1,] "1" "2" "3"
[2,] "2" "1" "3"
[3,] "3" "2" "1"
答案 1 :(得分:0)
不太优雅的答案,但这可以通过重塑来完成。
library(dplyr)
library(tidyr)
key =
rbind(c("a",1),c("b",2),c("c",3)) %>%
as.data.frame %>%
setNames(c("letter", "number"))
rbind(c("a","b","c"),c("b","a","c"),c("c","b","a")) %>%
as.data.frame %>%
mutate(ID = 1:n()) %>%
gather(variable, letter, -ID) %>%
left_join(key) %>%
select(-letter) %>%
spread(variable, number)