![](/img/trans.png)
[英]Using dplyr, how should I create a column of strings repeating a character based on the value of another column?
[英]how to renew column values based on part of character value in another column using dplyr?
我有兩列的大型數據框。 我想根據左列中部分字符值來續訂右列。
這是一個例子:
df <- structure(list(content = c("my new info", "information2",
"information3", "information4", "my new information2", "my new information3",
"information5", "information6", "information7", "information8"
), content_new = c("no new info", "no new info", "no new info",
"no new info", "no new info", "no new info", "no new info", "no new info",
"no new info", "no new info")), .Names = c("content", "content_new"
), class = "data.frame", row.names = c(NA, 10L))
print(df)
content content_new
1 my new info no new info
2 information2 no new info
3 information3 no new info
4 information4 no new info
5 my new information2 no new info
6 my new information3 no new info
7 information5 no new info
8 information6 no new info
9 information7 no new info
10 information8 no new info
這是我需要的結果:
content content_new
1 my new info no new info
2 information2 no new info
3 information3 no new info
4 information4 no new info
5 my new information2 my new information2
6 my new informatino3 my new informatino3
7 information5 no new info
8 information6 no new info
9 information7 no new info
10 information8 no new info
我要實現的規則是:如果內容包括“新信息”,則將值放在content_new中。 我嘗試了這段代碼:
library(dplyr)
newdf <- mutate(df, content_new = ifelse(grepl("new information",content,fixed==FALSE) == TRUE,content,content_new))
我收到此錯誤:
Error in function (string) :
comparison (1) is possible only for atomic and list types
有誰知道為什么會這樣以及我如何解決這個問題? 提前謝謝了!
您必須使用fixed = FALSE
而不是fixed == FALSE
:
mutate(df, content_new = ifelse(grepl("new information", content, fixed = FALSE),
content, content_new))
content content_new
1 my new info no new info
2 information2 no new info
3 information3 no new info
4 information4 no new info
5 my new information2 my new information2
6 my new informatino3 no new info
7 information5 no new info
8 information6 no new info
9 information7 no new info
10 information8 no new info
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.