1

I have a column of dataframe which is like "0.496,0.424,0.141". Now I would like to convert each of them to numeric and calculate the mean value. Could anyone tell me how can I do that? Thank you in advance.

string1 <- "0.496,0.424,0.141"
#I have try 
mean(as.numeric(string1))
#but it didnot work
Codezy
  • 662
  • 5
  • 17
  • split string (`strsplit`): `lapply(strsplit("0.496,0.424,0.141", ","), function(x) mean(as.numeric(x)))` – pogibas Apr 23 '19 at 09:13

2 Answers2

7

We could use read.csv and then use rowMeans to get mean of every row.

rowMeans(read.csv(text = string1, header = FALSE))
#[1] 0.3536667

The same would work with read.table as well

rowMeans(read.table(text = string1, sep = ","))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
1

Slightly more verbose than @RonakShah's solution, but maybe more understandable for beginners:

mean(as.numeric(unlist(strsplit(string1, split = ","))))
[1] 0.3536667

Explanation

strsplit() - split the string into a list at each comma, then
unlist() - turn the list into a vector, then
as.numeric() - convert each value of the vector into numeric (= float) type, then
mean() - calculate the mean of the resulting vector

Roman
  • 4,744
  • 2
  • 16
  • 58