简体   繁体   English

如何在 R 上的 data.frame 中添加新的多行?

[英]How to add new multiple rows to data.frame on R?

Below is how my code and dataframe looks like.下面是我的代码和 dataframe 的样子。

#Get country counts
countries <- as.data.frame(table(na.omit(co_df$country)))
print(countries)
 Var1 Freq
1  Austria    6
2   Canada    4
3   France    1
4  Germany   23
5    India   17
6    Italy    1
7   Russia    2
8   Sweden    1
9       UK    2
10     USA   10

I would like to add 4 new rows to the above countries data frame such that it looks like the below:我想在上述国家数据框中添加 4 个新行,如下所示:

Var1 Freq
1  Austria    6
2   Canada    4
3   France    1
4  Germany   23
5    India   17
6    Italy    1
7   Russia    2
8   Sweden    1
9       UK    2
10     USA   10
11     Uruguay   25
12     Saudi Arabia   19
13     Japan   11
14     Australia   10

I performed the below rbind function but it gave me an error;我执行了下面的 rbind function 但它给了我一个错误; I also tried merge(countries, Addcountries, by = Null) and the as.data.frame function but these too gave me errors.我还尝试merge(countries, Addcountries, by = Null)as.data.frame function 但这些也给了我错误。

Addcountries <- data.frame(c(11, 12, 13, 14), c("Uruguay", "Saudi Arabia", "Japan", "Australia"), c("25", "19", "11", "10"))
names(Addcountries) <- c("Var1", "Freq")
countries2 <- rbind(countries, Addcountries)
print(countries2)

This is likely a silly issue but I would appreciate any help here since I'm new to R.这可能是一个愚蠢的问题,但我会很感激这里的任何帮助,因为我是 R 的新手。

you may also use dplyr::add_row()你也可以使用dplyr::add_row()

countries %>% add_row(Var1 = c("Uruguay", "Saudi Arabia", "Japan", "Australia"), 
                           Freq = c(25, 19, 11, 10))

check it核实

countries <- read.table(text = " Var1 Freq
Austria    6
Canada    4
France    1
Germany   23
India   17
Italy    1
Russia    2
Sweden    1
UK    2
USA   10", header =T)

countries %>% add_row(Var1 = c("Uruguay", "Saudi Arabia", "Japan", "Australia"), 
                      Freq = c(25, 19, 11, 10))

           Var1 Freq
1       Austria    6
2        Canada    4
3        France    1
4       Germany   23
5         India   17
6         Italy    1
7        Russia    2
8        Sweden    1
9            UK    2
10          USA   10
11      Uruguay   25
12 Saudi Arabia   19
13        Japan   11
14    Australia   10

Create a dataframe with two columns and rbind .创建具有两列和rbind的 dataframe 。

Addcountries <- data.frame(Var1 = c("Uruguay", "Saudi Arabia", "Japan", "Australia"), 
                           Freq = c(25, 19, 11, 10), stringsAsFactors = FALSE)
countries2 <- rbind(countries, Addcountries)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM