简体   繁体   中英

adding a new column to a data.frame in r

I have a data.frame which has three column, here is part of the data:

variable lat lon 
140      40  120
120      41  120
115      42  120
...

This is the rainfall data for different stations. I want to add station-ID as the first column to the above data.frame which is an 1*n array where "n" is the total number of stations.

dat <- structure(list(variable = c(140L, 120L, 115L), lat = 40:42, lon = c(120L, 
120L, 120L)), .Names = c("variable", "lat", "lon"), class = "data.frame", row.names = c(NA, 
-3L))

#> dat
#  variable lat lon
#1      140  40 120
#2      120  41 120
#3      115  42 120

If you mean that each row is a unique station and you want ID s to run from top to bottom in order then transform is a nice clean way:

dat <- transform(dat, ID = 1:nrow(dat))  

# equivalently: dat <- transform(dat, ID = seq(length(variable)))
#> dat
#  variable lat lon ID
#1      140  40 120  1
#2      120  41 120  2
#3      115  42 120  3

You say you want ID as the first column and so you'll have to something like:

dat <- data.frame(ID = dat[,4], dat[,1:3])
#> dat
#  ID variable lat lon
#1  1      140  40 120
#2  2      120  41 120
#3  3      115  42 120

or simply cut out the middle man and ...

dat <- data.frame(ID = 1:nrow(dat), dat[,1:3])

# :)

Datas :

df <- read.table(header=T, text="variable lat lon 
+ 140      40  120
+ 120      41  120
+ 115      42  120")

Create a vector from 1 to n (number of stations) and add it to your data.frame

df$stationID <- seq(1,length(df[,1]),1)

That will work if you don't need to merge (if there is no duplicated stations).

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