按字符过滤,创建带有结果的列

时间:2019-05-17 09:26:22

标签: r string dplyr

我正在尝试创建一个显示两个数据集的图形,无论是那个字符还是不是那个字符。

目前我正在使用类似的东西

setosa <-  iris%>%
  filter_all(any_vars(str_detect(., pattern = "setosa")))

以虹膜示例为例,我希望能够在字符串中搜索一个字符,例如:setosa,然后绘制一个显示setosanot setosa的图形。

请参见下面的数据框示例,pd.Sails列充满了相同字符的不同含义。我希望能够绘制pd $ TWA v pd.TWS的图形,并且数据显示基于名称的pd $ Sails列的结果,因此J2 Nnot J2 N

很抱歉离开虹膜,我正在努力传达问题!

我当前的df是:


 pd.Boat   pd.Sails pd.TWA pd.TWS
1  Sojana RMAIN/J2 N   40.9   13.7
2  Sojana RMAIN/J2 N   38.8   13.0
3  Sojana RMAIN/J2 N   37.8   13.3
4  Sojana RMAIN/J2 N   37.3   13.3
5  Sojana RMAIN/J2 N   45.2   13.2
6  Sojana RMAIN/J2 N   50.6   13.2

dput(head)

structure(list(pd.Boat = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = "Sojana", class = "factor"), 
    pd.Sails = structure(c(36L, 36L, 36L, 36L, 36L, 36L), .Label = c("RMAIN", 
    "RMAIN/A2", "RMAIN/A2 C - north 19", "RMAIN/A2 C - north 19/Big Jonny", 
    "RMAIN/A2 C - north 19/CMiz SS", "RMAIN/A2 C - north 19/Spi SS v2/Big Jonny", 
    "RMAIN/A2 Doyle", "RMAIN/A2 Doyle/Big Jonny", "RMAIN/A2 Doyle/Spi SS v2", 
    "RMAIN/A2 Doyle/Spi SS v2/Big Jonny", "RMAIN/A2 N", "RMAIN/A2 N/Big Jonny", 
    "RMAIN/A2 N/Mizzen SS V2", "RMAIN/A2 N/Spi SS v2/Big Jonny", 
    "RMAIN/A2/Big Jonny", "RMAIN/A2/Big Jonny/Spi SS v2", "RMAIN/A2/Mizzen SS V2", 
    "RMAIN/A2/Spi SS v2", "RMAIN/A2/Spi SS v2/Big Jonny", "RMAIN/A2/Spi SS v2/Mizzen SS V2", 
    "RMAIN/A2N", "RMAIN/A2N/Big Jonny", "RMAIN/A2N/Mizzen SS V2", 
    "RMAIN/A2N/Spi SS v2/Big Jonny", "RMAIN/A4", "RMAIN/A4/Big Jonny", 
    "RMAIN/A4/Big Jonny/Mizzen SS V2", "RMAIN/A4/CMiz SS", "RMAIN/A4/J2 N/Big Jonny", 
    "RMAIN/A4/Mizzen SS V2", "RMAIN/A4/Spi SS v2/Big Jonny", 
    "RMAIN/J1 N", "RMAIN/J1 N/Black Betty v2", "RMAIN/J1 N/CMiz SS", 
    "RMAIN/J1 N/Mizzen SS V2", "RMAIN/J2 N", "RMAIN/J2 N/Black Betty v2", 
    "RMAIN/J2 N/CMiz SS", "RMAIN/J2 N/Mizzen SS V2"), class = "factor"), 
    pd.TWA = c(40.9, 38.8, 37.8, 37.3, 45.2, 50.6), pd.TWS = c(13.7, 
    13, 13.3, 13.3, 13.2, 13.2)), row.names = c(NA, 6L), class = "data.frame")

1 个答案:

答案 0 :(得分:1)

您可以使用ifelse来完成此操作。

iris$sns <- ifelse(iris$Species == "setosa", "setosa", "notsetosa")

set.seed(357)
iris <- iris[sample(1:nrow(iris)),]

> head(iris[sample(1:nrow(iris)),])
   Sepal.Length Sepal.Width Petal.Length Petal.Width    Species       sns
17          5.4         3.9          1.3         0.4     setosa    setosa
9           4.4         2.9          1.4         0.2     setosa    setosa
42          4.5         2.3          1.3         0.3     setosa    setosa
34          5.5         4.2          1.4         0.2     setosa    setosa
96          5.7         3.0          4.2         1.2 versicolor notsetosa
68          5.8         2.7          4.1         1.0 versicolor notsetosa