[英]Extract Column from data.frame as a Vector
我是 R 的新手。
我有一個 Data.frame,其中有一列名為“Symbol”。
Symbol
1 "IDEA"
2 "PFC"
3 "RPL"
4 "SOBHA"
我需要將其值存儲為向量( x = c("IDEA","PFC","RPL","SOBHA")
)。 哪種方法最簡潔?
your.data <- data.frame(Symbol = c("IDEA","PFC","RPL","SOBHA"))
new.variable <- as.vector(your.data$Symbol) # this will create a character vector
VitoshKa 建議使用以下代碼。
new.variable.v <- your.data$Symbol # this will retain the factor nature of the vector
你想要什么取決於你需要什么。 如果您將此向量用於進一步分析或繪圖,保留向量的因子性質是一個明智的解決方案。
這兩種方法有何不同:
cat(new.variable.v)
#1 2 3 4
cat(new.variable)
#IDEA PFC RPL SOBHA
Roman Luštrik 提供了一個很好的答案,但是, $
表示法通常很難在管道中使用。 在管道中,使用dplyr
函數pull()
。
# setting up
library(tidyverse)
# import tidyverse for dplyr, tibble, and pipe
df <- data.frame(Symbol = c("IDEA","PFC","RPL","SOBHA"))
> df
Symbol
1 IDEA
2 PFC
3 RPL
4 SOBHA
現在數據框已經設置好了,我們將首先對數據框進行一些隨機變異,以表明它可以在管道中工作,最后,我們將使用pull()
。
myvector <- df %>%
mutate(example_column_1 = 1:4, example_column_2 = example_column_1^2) %>% #random example function
arrange(example_column_1) %>% #random example function
pull(Symbol) # finally, the pull() function; make sure to give just the column name as an argument
您甚至可以在pull()
函數之后進一步操作管道中的向量。
> myvector
[1] IDEA PFC RPL SOBHA
Levels: IDEA PFC RPL SOBHA
> typeof(myvector)
[1] "integer"
typeof(myvector)
返回整數,因為這就是因子的存儲方式,因子的不同級別存儲為整數(我認為它們至少是這樣存儲的)。 如果要轉換為字符向量,只需使用as.character(myvector)
。
總之,當您想在管道中從數據框或 tibble 中提取向量時,請使用dplyr
的pull()
函數(並僅輸入您要提取的列名)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.