How to include a value in the last line of a data.frame in R

Asked

Viewed 634 times

1

I have a date.frame and a value in R, I needed this value to be included in the last row of a certain column of this date.frame. I’ve tested the function rbind but it didn’t work.

x <- c(1:15)
y <- c(1:15)
z <- 4
df <- data.frame(x,y)
df <- rbind(x, z)
  • The question is not well formulated. What is the expected answer to it, since df has two columns and z has only one observation? The last line should be formed by c(4, 4)? Or c(NA, 4)? Or else c(4, NA)? Please check this and be more clear about your needs.

  • Forgiveness, the value of Z should be included in the last line of X, therefore c(4, NA)

  • But x has only one dimension. By chance c(4, NA) should be the last line of df?

  • Yes, df should have 16 lines, and the last should be c(4, NA)

2 answers

2


Create the data frame z with the desired observations, making sure that the names of their columns match the names of the columns of df:

x <- c(1:15)
y <- c(1:15)
df <- data.frame(x,y)
names(df)
# [1] "x" "y"

z <- data.frame(x = 4, y = NA)
df <- rbind(df, z)
df
#     x  y
# 1   1  1
# 2   2  2
# 3   3  3
# 4   4  4
# 5   5  5
# 6   6  6
# 7   7  7
# 8   8  8
# 9   9  9
# 10 10 10
# 11 11 11
# 12 12 12
# 13 13 13
# 14 14 14
# 15 15 15
# 16  4 NA

0

You can add values at any positions directly, it is not necessary to create an object just for that:

df <- data.frame(x = 1:15,
                 y = 1:15)

df[nrow(df)+1, "x"] <- 4

> tail(df)
    x  y
11 11 11
12 12 12
13 13 13
14 14 14
15 15 15
16  4 NA

If the position already exists, the value is replaced. If not, the data.frame is resized and Nas inserted by default.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.