替换 df 列 R 中的(子字符串)特定字符
Replace (substring) specific characters in a df Column R
您好,我正在寻找一种方法来对 df 的列进行子字符串化。
Plot
1. Ctr-M1
2. Ctr-M2
3. CTR-W3
4. CTR-P-M20
5. M-1
6. W-15
substring_plot应该只包括W或M
我试过这样的东西
df$substring_plot = substr(df$plot,1,5,7)
哪个不行,我也明白为什么不行。起初我以为我可以这样做几次,直到我只剩下 W 和 M,但那很粗糙。
有人知道如何完成这项工作吗?
使用sub
:
df$plot_out <- sub("^.*([MW]).*$", "\1", df$plot)
df
plot plot_out
1 Ctr-M1 M
2 Ctr-M2 M
3 CTR-W3 W
4 CTR-P-M20 M
5 M-1 M
6 W-15 W
数据:
df <- data.frame(plot=c("Ctr-M1", "Ctr-M2", "CTR-W3", "CTR-P-M20", "M-1", "W-15"),
stringsAsFactors=FALSE)
您好,我正在寻找一种方法来对 df 的列进行子字符串化。
Plot
1. Ctr-M1
2. Ctr-M2
3. CTR-W3
4. CTR-P-M20
5. M-1
6. W-15
substring_plot应该只包括W或M 我试过这样的东西
df$substring_plot = substr(df$plot,1,5,7)
哪个不行,我也明白为什么不行。起初我以为我可以这样做几次,直到我只剩下 W 和 M,但那很粗糙。
有人知道如何完成这项工作吗?
使用sub
:
df$plot_out <- sub("^.*([MW]).*$", "\1", df$plot)
df
plot plot_out
1 Ctr-M1 M
2 Ctr-M2 M
3 CTR-W3 W
4 CTR-P-M20 M
5 M-1 M
6 W-15 W
数据:
df <- data.frame(plot=c("Ctr-M1", "Ctr-M2", "CTR-W3", "CTR-P-M20", "M-1", "W-15"),
stringsAsFactors=FALSE)