如果条件匹配,则粘贴字符串

时间:2019-05-15 14:09:25

标签: r if-statement

关于在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类别应为DukeCCMike类别的值应为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 有人可以看看吗?谢谢。

2 个答案:

答案 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))