我正试图摆脱一些角色:
list(structure(list(X1 = c("Station Name: Roches_Point", "Station Height: 40 M",
"Latitude:51.789", "Longitude: -8.240")), .Names = "X1", row.names = c(NA,
-4L), class = c("tbl_df", "tbl", "data.frame")), structure(list(
X1 = c("Station Name: Newport", "Station Height: 22 M", "Latitude:53.920",
"Longitude: -9.570")), .Names = "X1", row.names = c(NA, -4L
), class = c("tbl_df", "tbl", "data.frame")))
此功能可以实现我想要的功能,但我无法删除车站高度中的字母M.
metadata_list <- lapply(metadata_list, function(x)
sapply(x, function(y){
str_replace(y,"Station Name: |Station Height: | M|Latitude:|Longitude: ", "" )
}))
如果我只使用这个表达式再次运行它,它可以工作:
metadata_list <- lapply(metadata_list, function(x)
sapply(x, function(y){
str_replace(y," M", "" )
}))
只是好奇是什么原因?
答案 0 :(得分:1)
原因是您提供的模式将与该字符串的"Station Height: "
匹配,并替换一次并停在那里。您应该使用str_replace_all
来替换每个字符串中的所有匹配项。只需稍加改动:
metadata_list <- lapply(metadata_list, function(x)
sapply(x, function(y){
str_replace_all(y,"Station Name: |Station Height: | M|Latitude:|Longitude: ", "" )
}))
print(metadata_list)
[[1]]
X1
[1,] "Roches_Point"
[2,] "40"
[3,] "51.789"
[4,] "-8.240"
[[2]]
X1
[1,] "Newport"
[2,] "22"
[3,] "53.920"
[4,] "-9.570"