1

POSIXlt日付を保持するために使用しています。やりたいことは、各日付変数の月日を次のように変更することですが、エラーになります。(以下、d開催日一覧です。)

> d
[1] "2012-02-01 UTC"

> a = sapply(d, function(x) { x$mday=14;})
Warning messages:
1: In x$mday = 14 : Coercing LHS to a list
2: In x$mday = 14 : Coercing LHS to a list
3: In x$mday = 14 : Coercing LHS to a list
4: In x$mday = 14 : Coercing LHS to a list
5: In x$mday = 14 : Coercing LHS to a list
6: In x$mday = 14 : Coercing LHS to a list
7: In x$mday = 14 : Coercing LHS to a list
8: In x$mday = 14 : Coercing LHS to a list
9: In x$mday = 14 : Coercing LHS to a list
> a
  sec   min  hour  mday   mon  year  wday  yday isdst 
   14    14    14    14    14    14    14    14    14 

変数の形式が変わることに気付きました。

> class(d)
[1] "POSIXlt" "POSIXt" 

> a = sapply(d, function(x) { format(x, format = "%Y-%m-%d")})
> a
  sec   min  hour  mday   mon  year  wday  yday isdst 
  "0"   "0"   "0"  "14"   "1" "112"   "0"  "91"   "0" 

フォローしてもらうにはどうしたらいいですか

> d
    [1] "2012-02-14 UTC"

などの方法formatを試しました。as.POSIXlt何も機能しませんでした。

4

2 に答える 2

4

何が起こるか見てみましょう。簡単にするために、返す匿名関数を修正しますx

d <- as.POSIXlt(c('2012-02-01', '2012-02-02'), tz='UTC')
sapply(d, function(x) { x$mday=14; x})
#     sec min hour mday mon year wday yday isdst
#     0   0   0    1    1   112  3    31   0    
#     0   0   0    2    1   112  4    32   0    
#mday 14  14  14   14   14  14   14   14   14   
#Warning messages:
#1: In x$mday = 14 : Coercing LHS to a list
#2: In x$mday = 14 : Coercing LHS to a list
#3: In x$mday = 14 : Coercing LHS to a list
#4: In x$mday = 14 : Coercing LHS to a list
#5: In x$mday = 14 : Coercing LHS to a list
#6: In x$mday = 14 : Coercing LHS to a list
#7: In x$mday = 14 : Coercing LHS to a list
#8: In x$mday = 14 : Coercing LHS to a list
#9: In x$mday = 14 : Coercing LHS to a list

POSIXltオブジェクトはlist内部的には であり、lapply友達はそれをリストとして扱います。これは、関数mdayがこのリストの各要素に追加することで、それらをリストに変換することを意味します。

@akrunの回答は、これを行う方法を示しています。

于 2014-11-28T13:59:29.843 に答える
3

試す

d <- as.POSIXlt('2012-02-01', tz='UTC')
d$mday <- 14
d
#[1] "2012-02-14 UTC"
于 2014-11-28T13:46:12.280 に答える