Dol*_*cci 136 r vector type-conversion dataframe
我有一个数据框,如:
a1 = c(1, 2, 3, 4, 5)
a2 = c(6, 7, 8, 9, 10)
a3 = c(11, 12, 13, 14, 15)
aframe = data.frame(a1, a2, a3)
Run Code Online (Sandbox Code Playgroud)
我尝试以下将其中一列转换为向量,但它不起作用:
avector <- as.vector(aframe['a2'])
class(avector)
[1] "data.frame"
Run Code Online (Sandbox Code Playgroud)
这是我能提出的唯一解决方案,但我认为必须有更好的方法来做到这一点:
class(aframe['a2'])
[1] "data.frame"
avector = c()
for(atmp in aframe['a2']) { avector <- atmp }
class(avector)
[1] "numeric"
Run Code Online (Sandbox Code Playgroud)
注意:我的上述词汇可能已关闭,如果是,请纠正我.我还在学习R的世界.另外,对这里发生的事情的任何解释都是值得赞赏的(即与Python或其他语言相关的内容会有所帮助!)
jor*_*ran 184
我将尝试解释这一点而不会犯任何错误,但我打赌这会在评论中引起一两个澄清.
数据框是一个列表.使用列的名称对数据框进行子集时[
,您获得的是子列表(或子数据框).如果你想要实际的原子列,你可以使用[[
,或者有点混乱(对我来说)你可以做的aframe[,2]
,它返回一个向量,而不是一个子列表.
所以尝试运行这个序列,也许事情会更清楚:
avector <- as.vector(aframe['a2'])
class(avector)
avector <- aframe[['a2']]
class(avector)
avector <- aframe[,2]
class(avector)
Run Code Online (Sandbox Code Playgroud)
Jam*_*mes 30
你可以使用$
提取:
class(aframe$a1)
[1] "numeric"
Run Code Online (Sandbox Code Playgroud)
或双方括号:
class(aframe[["a1"]])
[1] "numeric"
Run Code Online (Sandbox Code Playgroud)
And*_*ēza 27
现在有一种简单的方法可以使用它dplyr
.
dplyr::pull(aframe, a2)
Run Code Online (Sandbox Code Playgroud)
Dir*_*tel 19
您不需要as.vector()
,但确实需要正确的索引:avector <- aframe[ , "a2"]
在另一件事情要注意的是drop=FALSE
选项[
:
R> aframe <- data.frame(a1=c1:5, a2=6:10, a3=11:15)
R> aframe
a1 a2 a3
1 1 6 11
2 2 7 12
3 3 8 13
4 4 9 14
5 5 10 15
R> avector <- aframe[, "a2"]
R> avector
[1] 6 7 8 9 10
R> avector <- aframe[, "a2", drop=FALSE]
R> avector
a2
1 6
2 7
3 8
4 9
5 10
R>
Run Code Online (Sandbox Code Playgroud)
使用'[['运算符的另一个好处是它可以与data.frame和data.table一起使用.因此,如果必须为data.frame和data.table运行该函数,并且您想从中提取一个列作为向量,那么
data[["column_name"]]
Run Code Online (Sandbox Code Playgroud)
是最好的.
小智 6
a1 = c(1, 2, 3, 4, 5)
a2 = c(6, 7, 8, 9, 10)
a3 = c(11, 12, 13, 14, 15)
aframe = data.frame(a1, a2, a3)
avector <- as.vector(aframe['a2'])
avector<-unlist(avector)
#this will return a vector of type "integer"
Run Code Online (Sandbox Code Playgroud)
如果您只使用提取运算符,它将起作用。默认情况下, [] 设置 option drop=TRUE
,这就是您在这里想要的。有关?'['
更多详细信息,请参阅。
> a1 = c(1, 2, 3, 4, 5)
> a2 = c(6, 7, 8, 9, 10)
> a3 = c(11, 12, 13, 14, 15)
> aframe = data.frame(a1, a2, a3)
> aframe[,'a2']
[1] 6 7 8 9 10
> class(aframe[,'a2'])
[1] "numeric"
Run Code Online (Sandbox Code Playgroud)