0

如果我有以下对象

[1] 0 1 0 0 0 0 0 0 0

如何将其转换为此,以便可以将其放在一列中并与数据框中的其他列对齐:

0
1
0
0
0
0
0

我认为list可能会起作用......但是这应该在哪个功能上起作用

很抱歉问了一个假设是基本问题......

4

2 回答 2

2

如果您有data.frame发言权,“DF”,如下所示:

DF <- data.frame(x=1:9, y=letters[1:9])

你有一个vectorz:

z <- c(0, 1, 0, 0, 0, 0, 0, 0, 0)

请注意,如果要将a添加为新列,则您的行数data.frame和长度必须相同。vectorvectordata.frame

dim(DF) # dimensions of data.frame
# [1] 9 2

length(z) # length of vector
# [1] 9

现在,您可以使用cbind如下方式获取新列:

cbind(DF, z)
#   x y z
# 1 1 a 0
# 2 2 b 1
# 3 3 c 0
# 4 4 d 0
# 5 5 e 0
# 6 6 f 0
# 7 7 g 0
# 8 8 h 0
# 9 9 i 0

如果您有一个vector长度不等于data.frame行的长度,那么,

z <- c(0, 1, 0, 0, 0, 0, 0) # length is 7

cbind(DF, z)
# Error in data.frame(..., check.names = FALSE) : 
#   arguments imply differing number of rows: 9, 7

cbind'ing 由于长度不等而导致错误。在这种情况下,我可以想出几种方法将其存储为list.

首先,您可以保持data.frameDF 原样并创建 a list,其第一个元素为 the data.frame,第二个元素为 a vector,如下所示:

my_l <- list(d1 = DF, d2 = z)

# $d1
#   x y
# 1 1 a
# 2 2 b
# 3 3 c
# 4 4 d
# 5 5 e
# 6 6 f
# 7 7 g
# 8 8 h
# 9 9 i
# 
# $d2
# [1] 0 1 0 0 0 0 0

或者,您可以将 your 转换data.frame为 a list(adata.frame在内部是 a list)并创建 a list,其元素vectors如下:

my_l <- c(as.list(DF), list(z=z))

# $x
# [1] 1 2 3 4 5 6 7 8 9
# 
# $y
# [1] a b c d e f g h i
# Levels: a b c d e f g h i
# 
# $z
# [1] 0 1 0 0 0 0 0

请注意,as.listdata.frame列强制转换为list具有其名称的列名称data.frame。然后我们创建一个新的listz 然后concatenate使用c操作符。

希望这能更好地理解你。

于 2013-03-30T10:11:51.530 回答
2

除了 Aruns 伟大而详细的回答外,还有两点值得注意:

首先,R回收较短的物品以匹配较长物品的长度。在将向量添加到 data.frame 的情况下,只有当 data.frame 的行数是向量长度的精确倍数时才会发生这种情况。

 zshort <- c(1, 2, 3)

# will be `0` if exact multiple:
length(zshort)  %/% nrow(DF)
# [1] 0

cbind(DF, zshort)
#  cbind(DF, zshort)
#  x y zshort
#  1 a      1
#  2 b      2
#  3 c      3
#  4 d      1   <~~ Recycling
#  5 e      2
#  6 f      3
#  7 g      1   <~~ Recycling
#  8 h      2
#  9 i      3

(2) 您还可以使用“[”向 data.frame 添加新列,如下所示:

# name of the column does NOT have to be
#  the same as the name of the vector
DF[, "newName"] <- z

DF[, "shortz"]  <- zshort

# You can also delete existing columns
DF[, "y"]  <- NULL

DF
#   x newName shortz
#   1       1      1
#   2       2      2
#   3       3      3
#   4       1      1
#   5       2      2
#   6       3      3
#   7       1      1
#   8       2      2
#   9       3      3
于 2013-03-30T12:34:44.157 回答