【问题标题】:Convert Vector From Dataframe从数据框转换向量
【发布时间】:2021-07-14 18:05:01
【问题描述】:

我使用以下代码创建了一个向量:

vectorA<-c(1.125,2.250,3.501)

我在数据框中存储了另一个向量:

vectordf<-data.frame()
vectordf[1,1]<-'1.125,2.250,3.501'
vectorB<-vectordf[1,1]

我需要vectorB 与vectorA 相同,这样我才能在另一个函数中使用它。现在这两个向量是不同的,如下所示:

printerA<-paste("vectorA=",vectorA)
printerB<-paste("vectorB=",vectorB)
print(printerA)
print(printerB)

dput(vectorA)
dput(vectorB)

[1] "vectorA= 1.125" "vectorA= 2.25"  "vectorA= 3.501"
[1] "vectorB= 1.125 2.250 3.501"
c(1.125, 2.25, 3.501)
"1.125 2.250 3.501"

如何将vectorB 转换为与vectorA 相同的格式?我尝试过使用 as.numeric、as.list、as.array、as.matrix。

【问题讨论】:

  • vectorB &lt;- scan(text = '1.125,2.250,3.501', sep = ",")?

标签: r list vector


【解决方案1】:

这可以通过scan 完成。

printerB<-paste("vectorB=", scan(text = vectordf[1,1], sep = ','))

现在printerAprinterB

printerA
#[1] "vectorA= 1.125" "vectorA= 2.25"  "vectorA= 3.501"
printerB
#[1] "vectorB= 1.125" "vectorB= 2.25"  "vectorB= 3.501"

【讨论】:

    【解决方案2】:

    问题在于,您所谓的“vectorB”并不像您想象的那样完全是一个向量——它是一个长度为 1 的 string 向量,由逗号分隔的数字组成。 p>

    您使用as.numeric() 的想法很好,但as.numeric() 不太清楚如何将带有逗号的字符串解析为不同数字的向量。所以,你首先要拆分字符串:

    vectorB <- unlist(strsplit(vectorB, ",", fixed = T))
    

    strsplit() 调用将根据找到逗号的位置将vectorB 分割成不同的向量子部分。它返回的数据结构是一个列表,因此我们将其展平为带有unlist() 的向量。 那么,你的as.numeric() 想法会奏效:

    vectorB <- as.numeric(vectorB)
    

    显然,如果您愿意,您可以将其整理成一行,但我想清楚地说明您的策略中的漏洞在哪里。


    为了使答案更完整:发生这种不匹配的原因是在您的代码早期的这一行中:

    vectordf[1,1]<-'1.125,2.250,3.501'
    

    &lt;-右侧的对象类型是一个字符串向量,它是一个长度为1的向量。要解决这个问题,你可以使用

    vectordf[1:3, 1] <- c(1.125, 2.25, 3.501)
    

    因为右侧对象的类型现在是长度为 3数字 向量。请注意,我们必须通过将行索引更改为 1:3 来调整左侧的索引。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-02
      • 2017-09-25
      • 1970-01-01
      • 2022-07-06
      • 2013-01-07
      相关资源
      最近更新 更多