Random insertion of a vector in a existing dataframe

Hello,
How can I randomly insert a given vector to an existing dataframe and gives the addition of the column?

(df <- data.frame(
  datetime=as.POSIXct(c("1976-09-04 04:00:00","1976-09-04 04:15:00",
                        "1976-09-04 04:30:00","1976-09-04 04:45:00")),
  temp=c(0,0,0,2.54)))

Suppose, T is added to the 3rd and 4th row in this expected outcome. It may be in the 1st and 2nd row or other possibilities.

T=c(2,7)

(df <- data.frame(
  datetime=as.POSIXct(c("1976-09-04 04:00:00","1976-09-04 04:15:00",
                        "1976-09-04 04:30:00","1976-09-04 04:45:00")),
 temp=c(0,0,7,9.54)))
(df <- data.frame(
  datetime=as.POSIXct(c("1976-09-04 04:00:00","1976-09-04 04:15:00",
                        "1976-09-04 04:30:00","1976-09-04 04:45:00")),
  temp=c(0,0,0,2.54)))

T=c(2,7)

df_length <- nrow(df)
add_length <- length(T)

row_to_add_to <- sample.int(n=df_length,
           size=add_length,
          replace = FALSE)

df$temp[row_to_add_to]<-df$temp[row_to_add_to] + T
df
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.