如何将列添加到 R 中的数据框?
在本文中,我们将了解如何在 R 中向数据框添加列。首先,让我们创建一个示例数据框。
将列添加到 DataFrame
我们可以使用 $ 符号向数据框中添加一列。
syntax: dataframe_name $ column_name = c( value 1,value 2 . . . , value n)
Here c() function is a vector holds values .we can pass any type of data with similar type.
向数据框添加列的步骤。
- 创建数据框。
- 使用上面语法中显示的 $ 符号将列添加到数据框中。
- 打印更新的数据框以查看更改。
示例 1:创建数据框。
R
# Creating a data frame with eid , ename,salary as columns
df2 = data.frame(eid = c(1, 2, 3),
ename = c("karthik", "nikhil", "sravan"),
salary = c(50000, 60000, 70000))
# printing the data frame
print(df2)
R
# creating a data frame
df2 = data.frame(eid = c(1, 2, 3),
ename = c("karthik", "nikhil", "sravan"),
salary = c(50000, 60000, 70000))
# adding a new column to the data frame using $ symbol
df2$designation = c("data scientist", "senior manager", "HR")
# printing the updated data frame
print(df2)
R
# creating a data frame using vectors
df1 = data.frame(id = c(1, 2 ,3),
name = c("karthik", "nikhil", "sravan"))
# printing the data frame
print(df1)
R
# creating a data frame
df1 = data.frame(id = c(1, 2, 3),
name = c("karthik", "nikhil", "sravan"))
# adding a new column to the data frame using $ symbol
df1$branch = c("IT", "CSE", "IT")
# printing the updated data frame
print(df1)
使用 $ 符号添加一列:
电阻
# creating a data frame
df2 = data.frame(eid = c(1, 2, 3),
ename = c("karthik", "nikhil", "sravan"),
salary = c(50000, 60000, 70000))
# adding a new column to the data frame using $ symbol
df2$designation = c("data scientist", "senior manager", "HR")
# printing the updated data frame
print(df2)
示例 2:创建数据框
电阻
# creating a data frame using vectors
df1 = data.frame(id = c(1, 2 ,3),
name = c("karthik", "nikhil", "sravan"))
# printing the data frame
print(df1)
向数据框中添加一列
电阻
# creating a data frame
df1 = data.frame(id = c(1, 2, 3),
name = c("karthik", "nikhil", "sravan"))
# adding a new column to the data frame using $ symbol
df1$branch = c("IT", "CSE", "IT")
# printing the updated data frame
print(df1)