省略所选变量之间的 space
Omit space between selected variables
我有一个名为 DATA_TEST.This 的数据集数据框包含字符 format.You 中的 7 个观察值,可以在下面看到 table。
#DATA SET
DATA_TEST<-data.frame(
Ten_digits=c("NA","207","0101","0208 90","0206 90 99 00","103","9706 00 00 00"),
stringsAsFactors = FALSE)
View(DATA_TEST)
所以我的目的是使用 stringr 或其他包转换此数据框,如下图所示。实际上,代码需要做一件事或更准确地说,首先必须只找到具有 10 个数字的变量,如“0206 90 99 00”或“9706 00 00 00”,并将这些变量转换为没有 space“0206909900”和“的变量9706000000”。在下面的 table 中,您终于可以看到 table 应该是什么样子了。
谁能帮我解决这个问题?
一种方法是在删除空格后计算字符数,并仅替换字符数为 10 的值。
temp <- gsub("\s", "", DATA_TEST$Ten_digits)
DATA_TEST$Ten_digits[nchar(temp) == 10] <- temp[nchar(temp) == 10]
DATA_TEST
# Ten_digits
#1 NA
#2 207
#3 0101
#4 0208 90
#5 0206909900
#6 103
#7 9706000000
您可以尝试 stringr
和 dplyr
:
DATA_TEST %>%
mutate(Ten_digits = if_else(str_count(Ten_digits, "[0-9]") == 10,
str_replace_all(Ten_digits, fixed(" "), ""),
Ten_digits))
Ten_digits
1 NA
2 207
3 0101
4 0208 90
5 0206909900
6 103
7 9706000000
或 stringr
和 base R
:
with(DATA_TEST, ifelse(str_count(Ten_digits, "[0-9]") == 10,
str_replace_all(Ten_digits, fixed(" "), ""),
Ten_digits))
我有一个名为 DATA_TEST.This 的数据集数据框包含字符 format.You 中的 7 个观察值,可以在下面看到 table。
#DATA SET
DATA_TEST<-data.frame(
Ten_digits=c("NA","207","0101","0208 90","0206 90 99 00","103","9706 00 00 00"),
stringsAsFactors = FALSE)
View(DATA_TEST)
所以我的目的是使用 stringr 或其他包转换此数据框,如下图所示。实际上,代码需要做一件事或更准确地说,首先必须只找到具有 10 个数字的变量,如“0206 90 99 00”或“9706 00 00 00”,并将这些变量转换为没有 space“0206909900”和“的变量9706000000”。在下面的 table 中,您终于可以看到 table 应该是什么样子了。
谁能帮我解决这个问题?
一种方法是在删除空格后计算字符数,并仅替换字符数为 10 的值。
temp <- gsub("\s", "", DATA_TEST$Ten_digits)
DATA_TEST$Ten_digits[nchar(temp) == 10] <- temp[nchar(temp) == 10]
DATA_TEST
# Ten_digits
#1 NA
#2 207
#3 0101
#4 0208 90
#5 0206909900
#6 103
#7 9706000000
您可以尝试 stringr
和 dplyr
:
DATA_TEST %>%
mutate(Ten_digits = if_else(str_count(Ten_digits, "[0-9]") == 10,
str_replace_all(Ten_digits, fixed(" "), ""),
Ten_digits))
Ten_digits
1 NA
2 207
3 0101
4 0208 90
5 0206909900
6 103
7 9706000000
或 stringr
和 base R
:
with(DATA_TEST, ifelse(str_count(Ten_digits, "[0-9]") == 10,
str_replace_all(Ten_digits, fixed(" "), ""),
Ten_digits))