我有一个巨大的数据框 df ,其中包含数字" a"我还有一个dataFrame 名称,其中包含与这些数字对应的名称。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Success page</title>
</head>
<body>
LEDon button pressed!!
</body>
</html>
现在我想用名字替换数字。新的dataFrame应如下所示:
df:
a b c name:
1 val1 val2 1 cat
1 val1 val2 2 dog
2 val1 val2 3 rabbit
3 val1 val2
3 val1 val2
3 val1 val2
我意识到这一点。它有效,但我不满足,因为我硬编码名称......
df:
a b c
cat val1 val2
cat val1 val2
dog val1 val2
rabbit val1 val2
rabbit val1 val2
rabbit val1 val2
如何从数据框名称中获取新值?
谢谢!
答案 0 :(得分:2)
这是合并两个data.frames。这不需要对任何值进行硬编码,只需要向data.frames添加新值
df <- data.frame(a = c(1,1,2,3,3,3), b = "val1", c = "val2")
df.name <- data.frame(a = 1:3, name=c("cat", "dog", "rabbit"))
df1 <- merge(df, df.name, by = "a") # merge two data.frames by `a`
如果您希望将名称存储在a
列
df1$a <- df1$name
df1$name <- NULL
a b c
1 cat val1 val2
2 cat val1 val2
3 dog val1 val2
4 rabbit val1 val2
5 rabbit val1 val2
6 rabbit val1 val2
答案 1 :(得分:1)
数据:
df = data.frame(a = c(1,1,2,3,3,3), b = rep('val1', 6), c = rep('val2', 6))
用字符替换值:
df$a = c('cat', 'dog', 'rabbit')[ match(df$a, sort(unique(df$a))) ]
输出
df
# a b c
#1 cat val1 val2
#2 cat val1 val2
#3 dog val1 val2
#4 rabbit val1 val2
#5 rabbit val1 val2
#6 rabbit val1 val2
答案 2 :(得分:1)
示例数据:
df = data.frame(a = c(1,1,2,3,3,3), b = rep('val1', 6), c = rep('val2', 6))
df
# a b c
# 1 1 val1 val2
# 2 1 val1 val2
# 3 2 val1 val2
# 4 3 val1 val2
# 5 3 val1 val2
# 6 3 val1 val2
使用dplyr
&#39; recode()
,您可以实现此目的:
df %>% mutate(a = recode(a, '1' = 'cat', '2' = 'dog', '3' = 'rabbit'))
# a b c
# 1 cat val1 val2
# 2 cat val1 val2
# 3 dog val1 val2
# 4 rabbit val1 val2
# 5 rabbit val1 val2
# 6 rabbit val1 val2