Reputation: 293
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.
Upvotes: 0
Views: 962
Reputation: 15441
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])
# :)
Upvotes: 1
Reputation: 1572
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).
Upvotes: 0