(就好像我重新阅读从CSV的数据R会做),你可以尝试type.convert
df1 <- df[1:3,]
str(df1)
# 'data.frame': 3 obs. of 4 variables:
# $ V1: chr "32" "12" "3"
# $ V2: chr "a" "b" "c"
# $ V3: chr "11" "32" "42"
# $ V4: chr "a" "b" "c"
df1[] <- lapply(df1, type.convert)
str(df1)
#'data.frame': 3 obs. of 4 variables:
#$ V1: int 32 12 3
#$ V2: Factor w/ 3 levels "a","b","c": 1 2 3
#$ V3: int 11 32 42
#$ V4: Factor w/ 3 levels "a","b","c": 1 2 3
要子集dataset
,你可以使用grep
(如@Richard斯克里文提到的评论)
indx <- grep('^v', df[,1])
df2 <- df[(indx+1):nrow(df),]
df2[] <- lapply(df2, type.convert)
假设,你的数据集有许多情况下,这种情况发生时,split
数据集基础上去除T后grepl
创建分组指数(indx1
)他标题行(indx
)并在“列表”中执行type.convert
。
indx1 <- cumsum(grepl('^v', df[,1]))+1
lst <- lapply(split(df[-indx,],indx1[-indx]), function(x) {
x[] <- lapply(x, type.convert)
x})
然后,如果你需要cbind
列(假设nrow
是所有列表中的元素一样)
dat <- do.call(cbind, lst)
你是怎么结束与摆在首位?可能最好找到引起这个问题并修复它,所以你不必再次这样做 – 2015-01-31 18:30:21