关于在r中粘贴函数,我有一个小问题。 这是我的桌子:
Name Value
AA 0
BB 1
CC 0
DD 1
EE 1
FF 1
GG 0
HH 1
我想做的是在Category
中获得另一个名为Table
的列,以Name
或{{1} },然后在AA
列中必须粘贴BB
,因为Category
类别应为Duke
,
CC
或Mike
类别的值应为DD
,依此类推。最后我应该得到
EE
Mark
Table
很大,无法手动进行设置,因此,有什么聪明的方法可以读取Name Value Category
AA 0 Duke
BB 1 Duke
CC 0 Mike
DD 1 Mark
EE 1 Mark
FF 1 Tom
GG 0 Hex
HH 1 Tom
列并粘贴到Table
列中吗? r中的任何循环函数或循环与粘贴函数的组合?我在stackoverflow上搜索,但找不到类似的情况。我在想的是这样的:
Name
有人可以看看吗?谢谢。
答案 0 :(得分:1)
可以在定义映射的位置使用命名向量。示例:
lookup_vector <- c(
AA = "Duke",
BB = "Duke",
CC = "Mike",
DD = "Mark",
EE = "Mark",
FF = "Tom",
GG = "Hex",
HH = "Tom"
)
Table[["Category"]] <- lookup_vector[Table[["Name"]]]
# Name Value Category
# 1 AA 0 Duke
# 2 BB 1 Duke
# 3 CC 0 Mike
# 4 DD 1 Mark
# 5 EE 1 Mark
# 6 FF 1 Tom
# 7 GG 0 Hex
# 8 HH 1 Tom
数据:
Table <- data.frame(
Name = c("AA", "BB", "CC", "DD", "EE", "FF", "GG", "HH"),
Value = c(0L, 1L, 0L, 1L, 1L, 1L, 0L, 1L)
)
答案 1 :(得分:0)
我们可以使用keyVal data.frame,然后使用left_join
library(dplyr)
keyVal <- structure(list(Name = structure(1:8, .Label = c("AA", "BB", "CC",
"DD", "EE", "FF", "GG", "HH"), class = "factor"), Category = structure(c(1L,
1L, 4L, 3L, 3L, 5L, 2L, 5L), .Label = c("Duke", "Hex", "Mark",
"Mike", "Tom"), class = "factor")), class = "data.frame",
row.names = c(NA, -8L))
library(dplyr)
left_join(df1, keyVal)
# Name Value Category
#1 AA 0 Duke
#2 BB 1 Duke
#3 CC 0 Mike
#4 DD 1 Mark
#5 EE 1 Mark
#6 FF 1 Tom
#7 GG 0 Hex
#8 HH 1 Tom
df1 <- structure(list(Name = structure(1:8, .Label = c("AA", "BB", "CC",
"DD", "EE", "FF", "GG", "HH"), class = "factor"), Value = c(0L,
1L, 0L, 1L, 1L, 1L, 0L, 1L)), class = "data.frame", row.names = c(NA,
-8L))