为数据框的每个列(变量)创建单独的向量 [英] Create separate vectors for each of a data frame's columns (variables)
问题描述
目标:获取一个数据框,并为其每个列(变量)创建单独的向量.
Goal: Take a data frame and create separate vectors for each of its columns (variables).
以下代码使我接近:
batting <- read.csv("mlb_2014.csv", header = TRUE, sep = ",")
hr <- batting[(batting$HR >= 20 & batting$PA >= 100), ]
var_names <- colnames(hr)
for(i in var_names) {
path <- paste("hr$", i, sep = "")
assign(i, as.vector(path))
}
它将为数据框中的每一列创建一个向量,如下所示:
It creates the a vector for each column in the data frame as shown by the output below:
> ls()
[1] "AB" "Age" "BA" "batting" "BB" "CS"
[7] "G" "GDP" "H" "HBP" "hr" "HR"
[13] "i" "IBB" "Lg" "Name" "OBP" "OPS"
[19] "OPS." "PA" "path" "Pos.Summary" "R" "RBI"
[25] "SB" "SF" "SH" "SLG" "SO" "TB"
[31] "Tm" "var_names" "X2B" "X3B"
到目前为止,一切都很好,直到您调用了其中一个向量.例如:
So far so good until you call one of the vectors. For example:
AB
[1] "hr$AB"
A,所有创建的都是一个元素的字符向量.当我想要创建它时...
Alas, all that is created is a one element character vector. When what I want it to create is this...
> AB <- as.vector(hr$AB)
> AB
[1] 459 456 506 417 492 496 404 430 497 346 494 501 415 370 500 331 501 539 456 443 316 437
[23] 449 526 349 486 432 480 295 489 354 506 315 471
...针对原始数据帧中的每个变量.
...for each variable in the original data frame.
如何让R将字符向量"path"中的元素识别为要在assign函数中调用的对象,而不是将单个字符元素分配给要创建的向量?我想将其保留在循环框架中,因为该项目的主要动机是教会我自己如何使用循环.
How do I get R to recognize the elements in the character vector "path" as objects to call in the assign function, rather than an individual character element to assign to the vector I'm creating? I would like to keep this within the loop frame work, since the main motivation behind this project is teach my self how to use loops.
谢谢!
推荐答案
为此,我们有 list2env
:
list2env(iris, .GlobalEnv)
head(Species)
#[1] setosa setosa setosa setosa setosa setosa
#Levels: setosa versicolor virginica
但是,几乎从来没有理由那样污染您的工作空间.
However, there is almost never a reason to pollute your workspace like that.
以下是您可以通过循环执行此操作的方法:
Here is how you can do this with a loop:
var_names <- colnames(iris)
for(i in var_names) {
assign(i, iris[[i]])
}
请注意,我使用 [[
]来访问data.frame列,而不是创建您的 path
.如果您将列名用作字符向量,则可以使用(或 [
])使用此字符来访问列.
Note that instead of creating your path
s I use [[
to access the data.frame columns. If you have a column name as a character vector, that (or [
) is the way to use this character to access the column.
这篇关于为数据框的每个列(变量)创建单独的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!