Convert units if row contains certain character string

Hello!

I have a dataset with some stations that have units in square miles and some that have units in square meters. If the SITE_ID starts with "NGL", then I want to convert its corresponding WGT_TP to square meters.

This is the code I tried, where I got a bunch of error messages:

allconvert <- all %>% 
  mutate(across(.cols=WGT_TP,
                .fns = ~ifelse(SITE_ID==grepl("NGL20"),.x*2589988.10,.x)))

Can someone help me figure out what I'm doing wrong? Below is a subset of my data.

all <- structure(list(SITE_ID = c("ISA20-40", "ISA20-42", "ISA20-43", 
"ISA20-46", "ISA20-55", "ISA20-57", "NGL20_IL-10001", "NGL20_IN-10001", 
"NGL20_IN-10002", "NGL20_MI-10088", "NGL20_MI-10089", "NGL20_MI-10090", 
"NGL20_MI-10091"), LK_REGION = c("Green Bay", "Main", "Main", 
"Main", "Main", "Main", "Main", "Main", "Main", "Main", "Green Bay", 
"Main", "Main"), ISLAND = c("Island", "Island", "Island", "Island", 
"Island", "Island", "", "", "", "", "", "", ""), STUDY = c("ISA20", 
"ISA20", "ISA20", "ISA20", "ISA20", "ISA20", "NGL20", "NGL20", 
"NGL20", "NGL20", "NGL20", "NGL20", "NGL20"), Latitude = c(45.1634, 
45.82730789, 45.76404832, 45.70623498, 45.00931488, 45.70007834, 
42.14156784, 41.66361184, 41.62668393, 43.10239715, 45.9345078, 
45.09776195, 44.31254922), Longitude = c(-87.3489, -85.4468549, 
-85.69480424, -85.43881237, -86.17475947, -85.6170888, -87.74541367, 
-87.26671873, -87.26838617, -86.27176684, -85.71997318, -85.69919414, 
-86.29954463), DO = c(11.3, 11.85, 10.35, 11.6, 10.9, 10.35, 
9.15, 12.5, 11.45, 12.025, 11.7, 10.9, 8.85), MEAN_SECCHI = c(2.85, 
9.35, 8.7, 9.1, 7.1, 6.75, 2.683333333, 5.490219038, 3.383333333, 
9.65, 10.15, 12.2, NA), WGT_TP = c(27254293.48, 356940135.5, 
356940135.5, 356940135.5, 356940135.5, 356940135.5, 181.3491184, 
65.02132203, 65.02132203, 61.4174063, 61.4174063, 61.4174063, 
61.4174063)), row.names = 69:81, class = "data.frame")

Thanks so much!

I discovered an alternate way to do it, but I'd be very interested in learning how to do it with mutate as well.

all$WGT_TP <- ifelse(grepl("NGL20", all$SITE_ID), all$WGT_TP*2589988.10, all$WGT_TP)

Here are two solutions using mutate().

allconvert <- all %>% 
  mutate(across(.cols=WGT_TP,
                .fns = ~ifelse(grepl("NGL20",SITE_ID),.x*2589988.10,.x)))

allconvert2 <- all %>% 
  mutate(WGT_TP=ifelse(grepl("NGL20",SITE_ID),WGT_TP*2589988.10,WGT_TP))
1 Like

Ah yes, I wasn't using the grepl syntax correctly. Appreciate your help, as always!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.