簡體   English   中英

如何在R中的Matrix中更改列?

[英]How to change column in Matrix in R?

Test
N        Date Column2  
1  2015-07-15      56   
2  2015-04-17      45

如何更改的日期一欄用實數列,我想改變每個日期的數日的一個月中,例如2015-07-15更改為72014-05-135

首先轉換為數據框:

as.data.frame(mat)
  N       Date Column2
1 1 2015-07-15      56
2 2 2015-04-17      45

然后使用正則表達式提取相關數據:

newdf$Date <- as.numeric(sub(".*-(.*)-.*", "\\1", newdf$Date))
newdf
  N Date Column2
1 1    7      56
2 2    4      45

正則表達式在許多編程語言中都很重要。 有關出色的教程和說明,請嘗試http://www.regular-expressions.info/tutorial.html


如果您想使用Date向量,則可以嘗試其他方法。

在像上面第一步中那樣轉換為數據幀之后:

newdf <- as.data.frame(mat)
newdf$Date <- as.Date(newdf$Date)
newdf$Date <- as.numeric(format(newdf$Date, "%m"))

現在,如果我們要按照您在注釋中指示的方式進行子集化:

newdf[newdf$Date == 7,]
  N Date Column2
1 1    7      56

為什么不只是

df <- data.frame(
  N=c(1,2),
  Date=c("2015-07-15","2014-04-21"),
  Column2=c(56,45)
)
df

df$Date <- as.numeric(format(as.Date(df$Date), "%m"))

暫無
暫無

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

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