如何在R中使用具有相同名称的向量值来命名数据框列?
要更改R中数据框的列名,我们可以使用setNames函数。例如,如果我们有一个名为df的数据框,其中包含列x,并且我们想将其更改为存储在名为x的向量中的值“Ratings”,那么我们可以使用代码df<-data.frame(x=sample(1:10,20,replace=TRUE))。
示例
考虑以下数据框
> x<-"Ratings" > y<-data.frame(x=sample(1:10,20,replace=TRUE)) > y
输出
x 1 3 2 8 3 3 4 9 5 5 6 5 7 10 8 2 9 6 10 6 11 3 12 5 13 9 14 1 15 1 16 6 17 2 18 6 19 10 20 6
将y中的x更改为Ratings
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
示例
> y<-setNames(y,x) > y
输出
Ratings 1 3 2 8 3 3 4 9 5 5 6 5 7 10 8 2 9 6 10 6 11 3 12 5 13 9 14 1 15 1 16 6 17 2 18 6 19 10 20 6
让我们看看另一个例子
示例
> S<-"Salary" > df_Salary<-data.frame(S=sample(20000:50000,20,replace=TRUE)) > df_Salary
输出
S 1 31827 2 24697 3 45790 4 45345 5 22294 6 30749 7 37721 8 33535 9 45941 10 24028 11 48927 12 33818 13 49152 14 43334 15 20294 16 29664 17 23358 18 20475 19 39355 20 40386
将df_Salary中的S更改为Salary
示例
> df_Salary<-setNames(df_Salary,S) > df_Salary
输出
Salary 1 31827 2 24697 3 45790 4 45345 5 22294 6 30749 7 37721 8 33535 9 45941 10 24028 11 48927 12 33818 13 49152 14 43334 15 20294 16 29664 17 23358 18 20475 19 39355 20 40386
广告