0

My current dataframe looks like this

site   tree
 Y      Y1
 Y      Y2
 Y      Y3
 C      C1
 C      C2
 F      F1
 F      F2

I would like to add an additional column that is basically the latitude that corresponds to each site ("C" = 67.31949N,"F" = 65.50790N,"Y" = 65.84669N). How can I do this in r? Thanks for any suggestions!

What I want my dataframe to look like

Site    Tree   Latitude
  Y      1     65.84669N
  Y      2     65.84669N
  Y      3     65.84669N
  C      1     67.31949N
  C      2     67.31949N
  F      1     65.50790N
  F      2     65.50790N
rrachel95
  • 43
  • 6

2 Answers2

1
xyz <- c("C" = "67.31949N", "F" = "65.50790N", "Y" = "65.84669N")
dat$Latitude <- xyz[ dat$Site ]
dat
#   Site Tree  Latitude
# 1    Y    1 65.84669N
# 2    Y    2 65.84669N
# 3    Y    3 65.84669N
# 4    C    1 67.31949N
# 5    C    2 67.31949N
# 6    F    1 65.50790N
# 7    F    2 65.50790N

Better, though, is to have the reference data in a frame,

ref <- data.frame(
  site = c("C","F","Y"),
  Latitude = c("67.31949N", "65.50790N","65.84669N"),
  Longitude = c("75W", "76E", "77W")
)
merge(dat, ref, by = "site", all.x = TRUE)
#   site tree  Latitude Longitude
# 1    C   C1 67.31949N       75W
# 2    C   C2 67.31949N       75W
# 3    F   F1 65.50790N       76E
# 4    F   F2 65.50790N       76E
# 5    Y   Y1 65.84669N       77W
# 6    Y   Y2 65.84669N       77W
# 7    Y   Y3 65.84669N       77W

Data

dat <- structure(list(site = c("Y", "Y", "Y", "C", "C", "F", "F"), tree = c("Y1", 
"Y2", "Y3", "C1", "C2", "F1", "F2")), class = "data.frame", row.names = c(NA, 
-7L))
r2evans
  • 141,215
  • 6
  • 77
  • 149
0

Also a similar approach to @r2evans using match and values saved in a dataframe:

#Data
df <- structure(list(site = c("Y", "Y", "Y", "C", "C", "F", "F"), tree = c("Y1", 
"Y2", "Y3", "C1", "C2", "F1", "F2")), row.names = c(NA, -7L), class = "data.frame")

#Keys
keys <- data.frame(site=c('C','F','Y'),val=c('67.31949N','65.50790N','65.84669N'),stringsAsFactors = F)
#Match
df$Latitude <- keys[match(df$site,keys$site),'val']

  site tree  Latitude
1    Y   Y1 65.84669N
2    Y   Y2 65.84669N
3    Y   Y3 65.84669N
4    C   C1 67.31949N
5    C   C2 67.31949N
6    F   F1 65.50790N
7    F   F2 65.50790N
Duck
  • 39,058
  • 13
  • 42
  • 84