我创建了一个列表,其中包含多个列表.我试图确定从"价值"获得"关键"的有效方法.即如果我指定("猫"或"狗"),("鱼"或"鸡"),("马"或"驴")我怎样才能分别返回"宠物","食物"和"工作" .我试图创建一个带有for循环的方法,因为我不确定如何通过名称进行索引处理.
pet <- c("cat", "dog")
food <- c("fish", "chicken")
work <- c("horse", "donkey")
types <- c("pet", "food", "work")
animal.list <- vector(mode = "list", length = length(types))
names(animal.list) <- types
for (i in types)
{
animal.list[[i]] <- vector(mode = "list", length = length(c("a", "b")))
names(animal.list[[i]]) <- c("a", "b")
animal.list[[i]][["a"]] <- eval(parse(text = i))[[1]]
animal.list[[i]][["b"]] <- eval(parse(text = i))[[2]]
}
Run Code Online (Sandbox Code Playgroud)
我的尝试看起来像这样,但希望我可以使用某种(%in%)语句来更有效/更紧凑地执行它.
f <- function(x)
{
ret <- NULL
for (i in animals)
{
if(x == animal.list[[i]][["a"]] | x == animal.list[[i]][["b"]])
{ …Run Code Online (Sandbox Code Playgroud) 真的很沮丧.我只想区分data.table中的行.其中dif(n)=值(n) - 值(n-1).所以,与我的相比,结果应该移动1个位置,每个"变量"的第一个位置应该是NA.即dif应为(NA,4,-2,NA,1,-8).每个"变量的第一个值应该是NA,因为没有位置n-1.任何想法如何修改函数来实现这个?我真的想知道如何为了我自己的理解而使用rollapplyr来做这个.
谢谢.
data.table:
> dt
variable value
1: xyz 3
2: xyz 7
3: xyz 5
4: abc 9
5: abc 10
6: abc 2
> dt[,dif := rollapplyr(value, 2, function(x){r <- diff(x,lag = 1)}, align = "right"), by = list(variable)]
> dt
variable value dif
1: xyz 3 4
2: xyz 7 -2
3: xyz 5 4
4: abc 9 1
5: abc 10 -8
6: abc 2 1
Run Code Online (Sandbox Code Playgroud) 我无法在R中执行简单的矩阵算术,这令人感到困惑。这真的不可能吗?我想采用1个数据框中的值,并将其子跟踪到另一个数据框中的所有列。看起来像这样应该很容易,但是我什么也没找到,尽管有一个“心理”程序包可以作为功能,但不能给出预期的结果。似乎也没有必要。有小费吗。非常感激。
> NROW(arData1[c(gsub(" ", ".",portfolio1), "benchmark")])
[1] 51
> NCOL(arData1[c(gsub(" ", ".",portfolio1), "benchmark")])
[1] 4
> NROW(arData1[gsub(" ", ".", treasuries)])
[1] 51
> NCOL(arData1[gsub(" ", ".", treasuries)])
[1] 1
ExRet1 <- arData1[c(gsub(" ", ".",portfolio1), "benchmark")] - arData1[gsub(" ", ".", treasuries)]
Error in Ops.data.frame(arData1[c(gsub(" ", ".", portfolio1), "benchmark")], :
- only defined for equally-sized data frames
Run Code Online (Sandbox Code Playgroud) 我试图命名数据框的列,但动态选择数据框.知道为什么这不起作用吗?下面是一个例子,但在我的实际情况中,我得到了一个不同的错误.截至目前,我只想知道导致错误的原因:
文件错误(文件名,"r"):无法打开连接
另外:警告消息:
在文件中(文件名,"r"):
无法打开文件'df':没有这样的文件或目录
#ASSIGN data frame name dynamically
> assign(as.character("df"), data.frame(c(1:10), c(11:20)))
>
#IT WOrked
> df
c.1.10. c.11.20.
1 1 11
2 2 12
3 3 13
4 4 14
5 5 15
6 6 16
7 7 17
8 8 18
9 9 19
10 10 20
>
#Call the data frame dynamically, it works
> eval(parse(text = c("df")))
c.1.10. c.11.20.
1 1 11
2 2 12
3 3 13
4 4 14
5 5 15 …Run Code Online (Sandbox Code Playgroud)