重新转换R中的数据类型

Ale*_*exR 0 r type-conversion

我在大数据集中有一个数据子集,它不符合数据读入R时分配的原始数据类型.如何重新转换数据子集的数据类型,就像R只做R一样那个子集被读了?

示例:假设存在一个由变量1-4(v1到v4)组成的数据堆栈和一个以列名v5到v8开头的不同数据集.

  V1 V2 V3 V4
1 32  a 11  a
2 12  b 32  b
3  3  c 42  c
4 v5 v6 v7 v8
5  a 43  a 35
6  b 33  b 64
7  c 55  c 32
Run Code Online (Sandbox Code Playgroud)

如果我使用v5-v8创建一个新的df,如何自动将整个数据"重新转换"为适当的类型?(就像我要重新读取csv中的数据一样,R会这么做)

akr*_*run 6

你可以试试 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
Run Code Online (Sandbox Code Playgroud)

要使用子集dataset,您可以使用grep(如评论中提到的@Richard Scriven)

 indx <- grep('^v', df[,1])
 df2 <- df[(indx+1):nrow(df),]
 df2[] <- lapply(df2, type.convert)
Run Code Online (Sandbox Code Playgroud)

假设,您的数据集中有许多实例发生这种情况,split数据集基于在删除标题行()之后indx1创建的分组索引grepl(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})
Run Code Online (Sandbox Code Playgroud)

然后,如果你需要cbind列(假设nrow所有列表元素都相同)

 dat <- do.call(cbind, lst)
Run Code Online (Sandbox Code Playgroud)

  • @AlexR`bapply`将输出转换为`matrix`,它只能容纳一个`class`.因此,如果有任何字符列/元素,它会将整个矩阵转换为`character`类.`lapply`在这方面更安全,因为它将输出保持在列表环境中 (2认同)