r: Error: Must extract column with a single valid subscript

r: Error: Must extract column with a single valid subscript

我在数据框中有一列的值为:“Q1”、“Q2”、“Q3”等。我试图使用以下方法将字母“Q”与数值分开:

DF %>% separate(DF$tmp, c(NA, "Number"), "(?<=[A-Z])(?=[0-9])" ). 

我收到以下错误:

"Error: Must extract column with a single valid subscript. x Subscript var has size 452 but must be size 1. "

如果我使用手动创建数据框,我不会收到此错误:

df <- data.frame(x = c(NA, "Q1", "Q2", "Q10"))

df %>% separate(x, c(NA, "B"), "(?<=[A-Z])(?=[0-9])" )

但是我在使用现有数据框时确实遇到了错误(我检查过,is.dataframe returns TRUE

命令应该是

DF %>% 
    separate(tmp, c("Other", "Number"), "(?<=[A-Z])(?=[0-9])" )

您可以使用 tidyr::extract -

tidyr::extract(df, x, c("A", "B"), '(Q)(\d+)')

#     A    B
#1 <NA> <NA>
#2    Q    1
#3    Q    2
#4    Q   10

如果您只对数字部分感兴趣,还有很多其他选项。

#1.
tidyr::extract(df, x, "B", 'Q(\d+)')
#2.
sub('Q(\d+)', '\1', df$x)
#3.
sub('Q', '', df$x)
#4.
stringr::str_extract(df$x, '\d+')
#5.
readr::parse_number(df$x)