Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing a whole column in R [closed]

Tags:

replace

r

I have searched a lot and I didn't find an answer on this. Let's say we have some data from a .csv file(lets call it xx.csv). Something like this

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

You can put whatever you want in A, B, C,...Names, numbers, NAs etc. So, Whats the easiest way that I replace a whole column (lets say B) with another one external (I mean not one from the csv file)??

like image 851
Tony Avatar asked Oct 10 '13 12:10

Tony


2 Answers

With assignment:

data$B <- whatever
# or
data[, "B"] <- whatever
# or
data[["B"]] <- whatever
like image 122
Richie Cotton Avatar answered Oct 10 '22 09:10

Richie Cotton


First I set up 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 by a 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")
like image 38
Christian Avatar answered Oct 10 '22 07:10

Christian