Replacing an entire column in R

I searched a lot and I did not find an answer to this. Say we have some data from a CSV file (let's call it xx.csv). Something like that

Number  A  B  C ... Z
 1     .. ..  ..
 .
 .
 .
4000  .. ..  .. ... ...

You can put whatever you want in A, B, C, ... Names, numbers, NA, etc. So, the easiest way to replace the entire column (let's say B) with another external (I mean not one from the csv file)?

+4
source share
2 answers

With purpose:

data$B <- whatever
# or
data[, "B"] <- whatever
# or
data[["B"]] <- whatever
+14
source

First I set an example people.csv.

names <- c("Alice", "Bob", "Carol")
ages <- c(18,21,19)
eyecolor <- c("Blue", "Brown", "Brown")
df <- data.frame(names, ages, eyecolor)
write.csv(df, "people.csv")

Then I replace the age column with the height column:

height <- c(160, 180, 170)
df <- read.csv("people.csv")
df[["ages"]] <- height
colnames(df)[colnames(df) == "ages"] <- "height"
write.csv(df, "people.csv")
+2
source

All Articles