[R] Help with strings

Sarah Goslee @@r@h@go@|ee @end|ng |rom gm@||@com
Tue Sep 29 22:58:27 CEST 2020


Your desired output seems to be the same as your desired input in your
example, and your data frames have different column names.

Nonetheless, this bit of code will find rows with "alcohol" in column
3, and for those rows replace the contents of column 4 with column 3.
That may not be exactly what you're after, but should get you started.

lapply(mylist, function(x){
x[grepl("alcohol", x[, 3]), 4] <- x[grepl("alcohol", x[, 3]), 3]
x
})

Sarah

On Tue, Sep 29, 2020 at 4:24 PM André Luis Neves <andrluis using ualberta.ca> wrote:
>
> Dear all,
>
> I have had difficulties copying the word "alcohol" in the "vehicle" column
> to replace the string in the column "accident_type". It is a huge list but
> I have prepared a workable and simple example below and the desired
> output.  I am sure you guys can give me some advice on how to deal with
> this.
>
>  sapply( all_files, function(x) dim(x))
>       [,1]  [,2]  [,3]  [,4]
> [1,] 89563 69295 67446 39709
> [2,]    33    33    33    33
>
>
>
> ###Simple List
>
> A= data.frame(c("1", "2", "3", "4"),c(4:7),c("car", "byke", "alcohol",
> "motocycle"), c("alcohol", "cell_phone", "some_string", "fog"))
> colnames(A) <- c("id", "km","vehicle","accident_cause")
> A
>
>
> B= data.frame(c("1", "2", "3", "4"),c(4:7),c("car", "alcohol", "car",
> "motocycle"), c("alcohol", "some_string", "rain", "fog"))
> colnames(B) <- c("id", "km", "vehicle", "accident_type")
> B
>
>
> C= data.frame(c("1", "2", "3", "4"),c(4:7),c("car", "alcohol", "car",
> "alcohol"), c("alcohol", "some_string", "rain", "some_string"))
> colnames(C) <- c("id", "km", "vehicle", "accident_type")
> C
>
> mylist <- list(A=A,B=B,C=C)
> mylist
>
>
> ###Desired output
>
> A= data.frame(c("1", "2", "3", "4"),c(4:7),c("car", "byke", "alcohol",
> "motocycle"), c("alcohol", "cell_phone", "alcohol", "fog"))
> colnames(A) <- c("id", "km","vehicle","accident_cause")
> A
>
>
> B= data.frame(c("1", "2", "3", "4"),c(4:7),c("car", "alcohol", "car",
> "motocycle"), c("alcohol", "alcohol", "rain", "fog"))
> colnames(B) <- c("id", "km", "vehicle", "accident_type")
> B
>
>
> C= data.frame(c("1", "2", "3", "4"),c(4:7),c("car", "alcohol", "car",
> "alcohol"), c("alcohol", "alcohol", "rain", "alcohol"))
> colnames(C) <- c("id", "km", "vehicle", "accident_type")
> C
>
> mylist <- list(A=A,B=B,C=C)
> mylist
>
>
> ##Thank you very much,
>
> --
> Andre
>


-- 
Sarah Goslee (she/her)
http://www.numberwright.com



More information about the R-help mailing list