在R中将行/字符串转换为单个列



如果我有以下对象

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

我如何将它转换成这样,这样我就可以把它放在一个列中并且它与我的数据帧中的其他列对齐:

0
1
0
0
0
0
0

我认为list可能会起作用…但是在

上应该用哪个函数呢?

很抱歉问了一个很基本的问题…

如果你有一个data.frame,说"DF",像这样:

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

还有vector z:

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

注意如果您想将vector添加到data.frame作为新列,则data.frame中的行数和vector的长度必须相同。

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.frame DF,并创建list,其第一个元素为data.frame,第二个元素为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

或者,您可以将data.frame转换为list (data.frame在内部是list),并创建一个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的列名相同。然后使用c操作符创建一个新的list z和concatenate

除了arun精彩而详细的回答之外,还有两点值得注意:

首先,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

最新更新