查找行是否包含字符并创建新列以标记数据

时间:2018-08-03 12:26:17

标签: r

具有一个只有一列的数据帧,并且每行都要检查一下这些数据中是否包含“#”:

"https://example.com/test-ability/321#321"
"https://example.com/test-ability/"
"anothertext#"
"notwithwhatyousearch"

如何查找每行是否包含字符“#”并创建第二个新列,并将具有此字符的行标记为“ A”,将没有此字符的行标记为“ B”? 预期结果示例

"https://example.com/test-ability/321#321", "A"
    "https://example.com/test-ability/", "B"
    "anothertext#", "A"
    "notwithwhatyousearch", "B"

2 个答案:

答案 0 :(得分:2)

th:checked="${1 == 1}"/>

或基本的R解决方案:

df = data.frame(x = c("https://example.com/test-ability/321#321",
                      "https://example.com/test-ability/",
                      "anothertext#",
                      "notwithwhatyousearch"), stringsAsFactors = F)

library(dplyr)

df %>% mutate(flag = ifelse(grepl("#", x), "A", "B"))

#                                          x flag
# 1 https://example.com/test-ability/321#321    A
# 2        https://example.com/test-ability/    B
# 3                             anothertext#    A
# 4                     notwithwhatyousearch    B

答案 1 :(得分:-1)

尝试使用此Python代码,我对R语言了解不多,可能会为您提供参考:

ls=["https://example.com/test-ability/321#321",
"https://example.com/test-ability/",
"anothertext#",
"notwithwhatyousearch"]          #Creating Data Frame

length=len(ls)                   #Finding list length
for i in range(0, length):       #Iteration
    if('#' in ls[i]):
        print(ls[i],' A')
    else:
        print(ls[i],' B')