【问题标题】:Subsetting Data in R not working through a vectorR中的子集数据不通过向量工作
【发布时间】:2020-02-16 14:44:44
【问题描述】:

Scanario。

在数据营课程中,使用 R 清理数据:案例研究。在课程的最末端有一个练习,我们有 5 列(例如:1、2、3、4、5)数据集“att5”。只有第 1 列是 char,其中有字符,但 2:5 有数字,但它是 type(chars)。他们告诉我制作一个由索引为 (2,3,4,5) 的向量组成的向量 cols,并使用 sapply 在它们上使用 as.numeric 函数。

我的解决方案虽然有意义,但不起作用。我先分享他们的解决方案,然后再分享我的解决方案。请帮助我了解发生了什么。

数据营解决方案(工作)

# Define vector containing numerical columns: cols
cols <- -1

# Use sapply to coerce cols to numeric
att5[, cols] <- sapply(att5[, cols], as.numeric)

我的解决方案(不起作用)

# Define vector containing numerical columns: cols
cols <- c(2:5)

# Use sapply to coerce cols to numeric
att5[, cols] <- sapply(att5[, cols], as.numeric)

我收到此错误:下标类型列表无效

帮助我理解。 R中的新手。

【问题讨论】:

    标签: r


    【解决方案1】:

    您的解决方案在我的机器上完美运行。我能看到的唯一区别是cols &lt;- -1 属于"numeric" 类,而cols &lt;- c(2:5)[1] "integer"。如果你想知道两者的区别可以看看What's the difference between integer class and numeric class in R

    因此,对其解决方案进行逆向工程的一种方法是在numeric 类中生成colsseq 可以帮助做到这一点。

    cols <- seq(2,5,1)
    #class(cols)
    #[1] "numeric"
    att5[, cols] <- sapply(att5[, cols], as.numeric)
    # str(att5)
    # 'data.frame': 5 obs. of  5 variables:
    # $ att1: Factor w/ 5 levels "A","B","C","D",..: 1 2 3 4 5
    # $ att2: num  1 2 3 4 5
    # $ att3: num  1 2 3 4 5
    # $ att4: num  1 2 3 4 5
    # $ att5: num  1 2 3 4 5
    

    数据

    dput(att5)
    att5 <- structure(list(att1 = structure(1:5, .Label = c("A", "B", "C", 
    "D", "E"), class = "factor"), att2 = structure(1:5, .Label = c("1", 
    "2", "3", "4", "5"), class = "factor"), att3 = structure(1:5, .Label = c("1", 
    "2", "3", "4", "5"), class = "factor"), att4 = structure(1:5, .Label = c("1", 
    "2", "3", "4", "5"), class = "factor"), att5 = structure(1:5, .Label = c("1", 
    "2", "3", "4", "5"), class = "factor")), class = "data.frame", row.names = c(NA, 
    -5L))
    

    希望它对你有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-07
      • 2020-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      • 2019-11-28
      相关资源
      最近更新 更多