使用基于另一个列字符的两个变量之一创建列

问题描述 投票:0回答:1

我有一个如下所示的数据框:

地点 样本_年 意思是
安湖 2003 22
鸟湖 2003 22
树湖 2003 22
安河 2003 22
蒂姆河 2003 22
狗河 2003 22
苹果河 2003 22

我想创建一个新列,指定位置类型(如果是河流或湖泊):

地点 样本_年 意思是 位置类型
安湖 2003 22
鸟湖 2003 22
树湖 2003 22
安河 2003 22
蒂姆河 2003 22
狗河 2003 22
苹果河 2003 22

我已经尝试过,但没有成功:

df%>%
  mutate(location_type = ifelse(location(contains("River"), "river", "lake")))

有没有办法用 dplyr 管道来做到这一点?

r if-statement dplyr pipe
1个回答
0
投票

您可以在这里使用

stringr
str_detect()
功能。

df <- df %>%
  mutate(location_type = ifelse(str_detect(location, "River"), "river", "lake"))
© www.soinside.com 2019 - 2024. All rights reserved.