📜  如何从 R DataFrame 中提取一列到列表?

📅  最后修改于: 2022-05-13 01:55:24.787000             🧑  作者: Mango

如何从 R DataFrame 中提取一列到列表?

在本文中,我们将讨论如何在 R 编程语言中将 DataFrame 中的列提取到 List。

方法 1:将所有列转换为列表

在此方法中,我们将创建一个带有字符(名称)和整数(标记)类型数据的向量,并将其传递给学生数据框。同样,我们将这两个向量传递给列表并显示它们。

句法:

例子:



R
# vector with names
names=c("bobby","pinkey","rohith","gnanu")
 
# vector with marks
marks=c(78,90,100,100)
 
# pass these vectors as inputs
# to the dataframe
student=data.frame(names,marks)
 
print(student)
print("----------------")
 
# pass those vectors to list
student_list=list(names,marks)
print(student_list)


R
# vector with names
names=c("bobby","pinkey","rohith","gnanu")
 
# vector with marks
marks=c(78,90,100,100)
 
# pass these vectors as inputs
# to the dataframe
student=data.frame(names,marks)
print(student)
print("----------------")
 
# pass marks column  to list
print(list(student$marks))


R
# vector with names
names=c("bobby","pinkey","rohith","gnanu")
 
# vector with marks
marks=c(78,90,100,100)
 
# pass these vectors as inputs
# to the dataframe
student=data.frame(names,marks)
print(student)
print("----------------")
 
# pass all columns  to list
a=list(student$names,student$marks)
print(a)


R
# Creating a list
example_list <- list(P = 1:8,       
                Q = letters[1:8],
                R = 5)
example_list
 
# Extracting the values of Q only using $ operator
example_list$Q


输出:

方法 2:使用 $

R 中的 $运算符用于提取数据的特定部分或访问数据集中的变量。我们可以使用 $ 运算符将数据框列传递给列表。要选择的列将使用以 $ 分隔的数据框名称传递。

句法:

例子:

电阻



# vector with names
names=c("bobby","pinkey","rohith","gnanu")
 
# vector with marks
marks=c(78,90,100,100)
 
# pass these vectors as inputs
# to the dataframe
student=data.frame(names,marks)
print(student)
print("----------------")
 
# pass marks column  to list
print(list(student$marks))

输出:

我们可以使用相同的方法提取多于一列,然后再次将其传递给 list()函数。

例子:

电阻

# vector with names
names=c("bobby","pinkey","rohith","gnanu")
 
# vector with marks
marks=c(78,90,100,100)
 
# pass these vectors as inputs
# to the dataframe
student=data.frame(names,marks)
print(student)
print("----------------")
 
# pass all columns  to list
a=list(student$names,student$marks)
print(a)

输出:

例子 :

电阻

# Creating a list
example_list <- list(P = 1:8,       
                Q = letters[1:8],
                R = 5)
example_list
 
# Extracting the values of Q only using $ operator
example_list$Q

输出 :

我们可以从列表中的特定列中提取元素。