【问题标题】:Assigning new vectors in a dataframe using cbind () and data.frame()使用 cbind () 和 data.frame() 在数据框中分配新向量
【发布时间】:2018-06-07 12:13:14
【问题描述】:

我正在使用 cbind() 和 data.frame() 将向量放入数据框中。我想在构建数据框时添加一个新向量(价格/货币)。

花1: 使用 data.frame() 创建一个数据框; '=' 分配新向量

花2: 使用 cbind() 创建数据框; '=' 分配新向量

花3: 使用 data.frame() 创建数据框; '

花4: 使用 cbind() 创建数据框; '

flowers1 和 2 是我所期望的,但在 flowers3 中,第三列的标题是奇数。而在flowers4中,第三列的表头不见了。

我的问题是:

  1. 这是什么原因造成的?

  2. 使用 '

    (我只知道这两个assign方法有不同的优先级和不同的变量寿命?

  3. 创建数据帧时分配新向量是否违法或不建议?

谢谢!

name <- c('iris','daisy')
color <- c('purple','blue')
flowers1 <- data.frame(name,color,price = c(10,20))
flowers1
# output
name  color price
1  iris purple    10
2 daisy   blue    20

flowers2 <- cbind(name,color,price = c(10,20))
flowers2
# output
name    color    price
[1,] "iris"  "purple" "10" 
[2,] "daisy" "blue"   "20"

flowers3 <- data.frame(name,color,price <- c(10,20))
flowers3
# output
   name  color price....c.10..20.
1  iris purple                 10
2 daisy   blue                 20

flowers4 <- cbind(name,color,money <- c(10,20))
flowers4
# output
      name    color        
[1,] "iris"  "purple" "10"
[2,] "daisy" "blue"   "20"

【问题讨论】:

  • within中可以使用&lt;-,但在cbinddata.frame中,应该是=

标签: r


【解决方案1】:

使用 = 设置函数参数,使用

A = LETTERS[1:5]
B = letters[1:5]

d <- data.frame(A , B, CC <- seq(5, 1, -1))
d
CC # lives outside d!

d1 <- data.frame(A, B, DD = seq(5, 1, -1))
d1
DD # does not live outside d1

【讨论】:

    猜你喜欢
    • 2018-07-25
    • 2018-06-06
    • 1970-01-01
    • 2020-07-09
    • 2023-03-31
    • 2013-03-20
    • 1970-01-01
    相关资源
    最近更新 更多