簡體   English   中英

R,rowMean按data.frame中的列

[英]R, rowMeans by Column in data.frame

我有一個已讀入的csv,現在是R中的data.frame。我的文件名為MyRData007。 我的標題信息一直持續到第5行(主列標題位於第4行)。 我的ID在A列中。我只需要為每個ID創建兩個單獨的rowMeans。 數據在第5-147行中。 第一個意思是第4-15列; 第二個意思是第6-21列。 最終,我應該為143行中的每行都添加一個平均值。 這是我嘗試的:

> mRNA<-rowMeans(MyRData007)[5:147,(4:15)]
> Protein<-rowMeans(MyRData007)[5:147,(16:21)]

但是我得到一個錯誤?

Error in rowMeans(MyRData007) : 'x' must be numeric
df <- read.table(text='this is a header
                 this is another header
                 this too is one
                 and this is also
                 id code status value
                 1 2 3 4
                 2 32 43 23
                 3 3 43 32
                 4 232 323 55')
df
    V1   V2      V3     V4
1 this   is       a header
2 this   is another header
3 this  too      is    one
4  and this      is   also
5   id code  status  value
6    1    2       3      4
7    2   32      43     23
8    3    3      43     32
9    4  232     323     55

因此,當您嘗試調用rowMeans ,會出現錯誤:

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

之所以會出現此錯誤,是因為您試圖獲取非數字值的平均值,這沒有任何意義。 您嘗試對數據進行子集化的操作無效,因為您將方括號放在對rowMeans的調用rowMeans ,這告訴它對rowMeans的輸出進行子集rowMeans ,而不是對輸入的數據進行子集化。

基本的問題是,R data.frame不能包含標題信息。 數據框的一列中的所有數據都必須為同一類型,因此,如果某些行中包含字符,則其他行中不能包含數字。

您該如何解決?

使用skip = 4參數使用read.table讀入數據。 這將使其跳過標題信息行,以僅包含您的數據來生成數據幀。 如果文件是.csv ,則還需要指定sep=','header=T

df2 <- read.table(text='this is a header
                 this is another header
                 this too is one
                 and this is also
                 id code status value
                 1 2 3 4
                 2 32 43 23
                 3 3 43 32
                 4 232 323 55', skip = 4, header = T)
rowMeans(df2)
[1]   2.50  25.00  20.25 153.50

read.csv只是read.table的包裝,使用它與使用read.table以及以下選項相同:

read.table(file, header = TRUE, sep = ",", fill = TRUE)

通常,最好使用read.table因為它可以為您提供更多控制權。 最重要的示例是將stringsAsFactors = FALSE設置stringsAsFactors = FALSE以防止將字符串轉換為factors (一個非常煩人的默認值)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM