0

I'm an R noob, so I know this probably has a simple solution, but I can't figure it out. I'm trying to read in data that is deliminated by spaces. There are 5 columns and 1000 rows. I want to take the mean and median of each row and then calculate the mean-squared error and bias based off of both of mean and median.

I'm struggling to take the mean of individual rows, and I'm not sure what I'm doing wrong.

My data looks like:

X1                 X2               X3             X4           X5

-2.3564870e-02  -3.3810429e-01  -3.0566635e+00  -1.1046286e-02  -3.0032159e-01

    vals <- read.table("laplace_samples.dat")
    rowMeans(vals)

I always get the error:

Error in rowMeans(vals) : 'x' must be numeric

I would prefer to do this in a loop and look at the means individually, but I can't figure out how to do that, either. What I've tried:

    for(i in 2:1001){
       row = vals[i,1:5]
       mn = mean(row)
       med = median(row)
       ..... other code
    }

Also, is there I way I can convert it into a matrix so I can index vals[colnumber][rownumber] or something like that?

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
beth
  • 98
  • 3
  • 10
  • until you're used to R always look at what you read in ... `head(vals)` and /or `str(head(vals))`.... And a hint: try "header=TRUE" in your read.table – Glen_b Oct 20 '15 at 03:50

1 Answers1

1

This questions should be migrated on StackOverFlow. However...

Looks like you have a characters first row with X1 X2 X3 X4 X5. Use:

vals <- read.table("laplace_samples.dat", header = TRUE)
rowMeans(vals)

If the above code does not work try:

vals <- read.table("laplace_samples.dat")
vals <- as.numeric(vals)
rowMeans(vals)

If you want vals to be a matrix type:

vals <- as.matrix(vals)
stochazesthai
  • 617
  • 1
  • 7
  • 20
  • You can always flag to migrate ... but you can pretty much guarantee it will close there immediately (it's not reproducible as is); and anticipating that the flag would probably not be acted on. – Glen_b Oct 20 '15 at 03:51
  • You can't do `as.numeric(vals)` after `read.table()` as `as.numeric()` cannot be used directly on lists/data frames. Check `as.numeric(mtcars)` – Rich Scriven Oct 20 '15 at 03:58
  • Thank you so much! I was stuck for way too long! – beth Oct 20 '15 at 03:58