我有一個資料看起來像這樣但要大得多
df<- structure(list(names = c("bests-1", "trible-1", "crazy-1", "cool-1",
"nonsense-1", "Mean-1", "Lose-1", "Trye-1", "Trified-1"), Col = c(1L,
2L, NA, 4L, 47L, 294L, 2L, 1L, 3L), col2 = c(2L, 4L, 5L, 7L,
9L, 9L, 0L, 2L, 3L)), class = "data.frame", row.names = c(NA,
-9L))
例如,我試圖從第一列的所有字串中洗掉 -1
我可以這樣做
as.data.frame(str_remove_all(df$names, "-1"))
問題是它也會洗掉所有其他列。
我不想拆分資料并再次合并,因為我擔心我不匹配
反正有沒有中斷,只是突襲特定的字串?
例如輸出應該是這樣的
names Col col2
bests 1 2
trible 2 4
crazy NA 5
cool 4 7
nonsense 47 9
Mean 294 9
Lose 2 0
Try 1 2
Trified 3 3
uj5u.com熱心網友回復:
使用gsub, 轉義特殊的\\-, 和$用于字串結尾。
transform(df, names=gsub('\\-1$', '', names))
# names Col col2
# 1 bests 1 2
# 2 trible 2 4
# 3 crazy NA 5
# 4 cool 4 7
# 5 nonsense 47 9
# 6 Mean 294 9
# 7 Lose 2 0
# 8 Trye 1 2
# 9 Trified 3 3
資料:
df <- structure(list(names = c("bests-1", "trible-1", "crazy-1", "cool-1",
"nonsense-1", "Mean-1", "Lose-1", "Trye-1", "Trified-1"), Col = c(1L,
2L, NA, 4L, 47L, 294L, 2L, 1L, 3L), col2 = c(2L, 4L, 5L, 7L,
9L, 9L, 0L, 2L, 3L)), class = "data.frame", row.names = c(NA,
-9L))
uj5u.com熱心網友回復:
使用stringr包,
df$names = str_remove_all(df$names, '-1')
names Col col2
1 bests 1 2
2 trible 2 4
3 crazy NA 5
4 cool 4 7
5 nonsense 47 9
6 Mean 294 9
7 Lose 2 0
8 Trye 1 2
9 Trified 3 3
uj5u.com熱心網友回復:
我們可以使用trimws從base R
df$names <- trimws(df$names, whitespace = "-\\d ")
-輸出
> df
names Col col2
1 bests 1 2
2 trible 2 4
3 crazy NA 5
4 cool 4 7
5 nonsense 47 9
6 Mean 294 9
7 Lose 2 0
8 Trye 1 2
9 Trified 3 3
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/393437.html
標籤:r
上一篇:避免單詞在R中被刪減
