R中的错误:替换已。。。行,数据有…行 df

R中的错误:替换已。。。行,数据有…行 df,r,dataframe,if-statement,R,Dataframe,If Statement,grepl和ifelse是矢量化的,因此您不需要在此处应用 df <- data.frame(values = c(2.5, 12, 4.8, 56, 78), samples = c('45fe.K2', '59ji.K2', '59rc.K1', '45hi.K1', '96hu.K1')) df$group <- NA df$group <- apply(df,1,function(x) {ifelse(grepl('K2',df$samples) == TRUE,pa

grepl
ifelse
是矢量化的,因此您不需要在此处应用

df <- data.frame(values = c(2.5, 12, 4.8, 56, 78),
samples = c('45fe.K2', '59ji.K2', '59rc.K1', '45hi.K1', '96hu.K1'))

df$group <- NA
df$group <- apply(df,1,function(x)
{ifelse(grepl('K2',df$samples) == TRUE,paste('K2'),paste('K1'))})

Error in `$<-.data.frame`(`*tmp*`, "PANEL", value = c(1L, 2L, 2L, 2L,  : 
 replacement has ... rows, data has ....rows

要使代码正常工作,请尝试应用(df,1,函数(x){ifelse(grepl('K2',x[2]),“K2”,“K1”)}
,尽管我们不会这样编写代码,因为
grepl
ifelse
是矢量化的。
df$group <- ifelse(grepl('K2', df$samples), 'K2', 'K1')
df$group <- paste0('K', as.integer(grepl('K2', df$samples)) + 1)
#Or extract K1, K2 value from the string
df$group <- sub('.*(K\\d+).*', '\\1', df$samples)