I'm trying to create two new columns in a data frame, where one is the mean of each row and the median of each row. I tried using the rowMeans()function, but I get an error message.
what I have
n x z
A 43 5 9
B 23 33 7
C 8 4 67
D 95 13 43
type or paste code here
what I want
n x z avg med
A 43 5 9 19 9
B 23 33 7 21 23
C 8 4 67 26 8
D 95 13 43 50 43
type or paste code here
a <- readr::read_csv("/Users/ro/Desktop/grist.csv")
#> Rows: 4 Columns: 4
#> ── Column specification ────────────────────────────────────────────────────────
#> Delimiter: ","
#> chr (1): id
#> dbl (3): n, x, z
#>
#> ℹ Use `spec()` to retrieve the full column specification for this data.
#> ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
a
#> # A tibble: 4 × 4
#> id n x z
#> <chr> <dbl> <dbl> <dbl>
#> 1 A 43 5 9
#> 2 B 23 33 7
#> 3 C 8 4 67
#> 4 D 95 13 43
# save out and remove id column to create all numeric
id <- a[1]
a <- a[-1]
a$means <- rowMeans(a)
a$medians <- apply(a[,1:3],1,median)
a <- cbind(id,a)
a
#> id n x z means medians
#> 1 A 43 5 9 19.00000 9
#> 2 B 23 33 7 21.00000 23
#> 3 C 8 4 67 26.33333 8
#> 4 D 95 13 43 50.33333 43