简体   繁体   中英

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

Below is how my code and dataframe looks like.

#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:

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; I also tried merge(countries, Addcountries, by = Null) and the as.data.frame function but these too gave me errors.

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.

you may also use 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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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