如何按列名快速将命名值追加至DataFrame?
问题描述
我有一个包含6列的DataFrame:
col1|col2|col3|col4|col5|col6 1 3 4 r1 r2 5 5 3 2 s1 s2 5 5 4 2 x1 s2 5
同时我有6个命名值:
col1<-4 col2<-2 col3<-1 col4<-"f1" col5<-"s1" col6<-7
需要按对应列名将这些值追加至该DataFrame,得到目标结果。
解决方法
方法1:基础R的rbind()函数
先把命名值转换成和原DataFrame结构一致的单行数据框,再用rbind()完成追加:
# 先定义原DataFrame(假设名为df) df <- data.frame( col1 = c(1,5,5), col2 = c(3,3,4), col3 = c(4,2,2), col4 = c("r1","s1","x1"), col5 = c("r2","s2","s2"), col6 = c(5,5,5), stringsAsFactors = FALSE ) # 将命名值转为单行数据框 new_row <- data.frame( col1 = col1, col2 = col2, col3 = col3, col4 = col4, col5 = col5, col6 = col6, stringsAsFactors = FALSE ) # 追加行到原DataFrame df <- rbind(df, new_row)
方法2:用dplyr包的add_row()函数
如果使用tidyverse工具集,add_row()可以直接按列名传入值,写法更简洁:
library(dplyr) # 假设原DataFrame名为df,直接追加行 df <- df %>% add_row( col1 = col1, col2 = col2, col3 = col3, col4 = col4, col5 = col5, col6 = col6 )
注意:要确保新值的类型和对应列的类型一致,否则可能会出现类型不匹配的报错。
内容的提问来源于stack exchange,提问作者user35131
相关产品推荐
相关产品推荐

