R语言 如何从R数据框架中提取一列到一个列表

R语言 如何从R数据框架中提取一列到一个列表

在这篇文章中,我们将讨论如何在R编程语言中从DataFrame中提取一列到一个列表。

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

在这个方法中,我们将用字符(名字)和整数(分数)类型的数据创建一个向量,并传递给学生数据框架。同样地,我们将把这两个向量传递给列表并显示它们。

语法

list(col1, col2,…, col n)

例子

# 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)
Bash

输出

如何从R数据框架中提取一列到一个列表?

方法2:使用$

R中的操作符用于提取数据的特定部分或访问数据集中的某个变量。我们可以通过使用操作符用于提取数据的特定部分或访问数据集中的某个变量。我们可以通过使用操作符将数据框架的列传递给一个列表。要选择的列需要用$分隔的数据框架名称来传递。

语法

list(dataframe$column_name)

例子

# 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))
Bash

输出

如何从R数据框架中提取一列到一个列表?

我们可以用同样的方法提取一个以上的列,然后再次将其传递给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(studentnames,studentmarks)
print(a)
Bash

输出

如何从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_listQ
Bash

输出:

如何从R数据框架中提取一列到一个列表?

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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册