我有的数据框包含两个列:ID和类型(字符).见下文:
set.seed(123) ID <- seq(1,25) type <- sample(letters[1:26],25,replace=TRUE) df <- data.frame(ID,type)
我需要创建一个只包含一列的新数据框.第一次观察将是第一次
列类型中的三个字母,第二个观察是第二个三个字母,很快就开始了.
新数据看起来像
ndf <- data.frame(ntype=c("huk","wyb","nxo","lyl","roc","xgb","iyx","sqz","r"))
解决方法
我们使用gl创建一个分组变量,然后使用tapply将元素粘贴在一起
n <- 3 ndf <- data.frame(ntype = with(df,unname(tapply(type,as.integer(gl(nrow(df),n,nrow(df))),FUN =paste,collapse=""))),stringsAsFactors= FALSE) ndf$ntype #[1] "huk" "wyb" "nxo" "lyl" "roc" "xgb" "iyx" "sqz" "r"
或者另一种选择是将整个列粘贴在一起然后拆分
strsplit(paste(df$type,collapse=""),"(?<=.{3})",perl = TRUE)[[1]] #[1] "huk" "wyb" "nxo" "lyl" "roc" "xgb" "iyx" "sqz" "r"
或者另一个选项是带有粘贴的子串
substring(paste(df$type,seq(1,nrow(df),by = 3),c(seq(3,nrow(df))) #[1] "huk" "wyb" "nxo" "lyl" "roc" "xgb" "iyx" "sqz" "r"
注意:以上所有都是基本R解决方案