I am trying to apply values of a vector over a list of character vectors using lapply and a hand-crafted function that contains multiple for-loops. Argh! Essentially what I have is a list of character vectors that looks like this (filename_lists3
):
$`809`
[1] "rakelib/blueprint.rb" "projects/daedalus/daedalus.rb"
$`859`
[1] "README"
...
and a named, numeric vector that looks like this (degree_list
):
projects/daedalus/daedalus.rb rakelib/blueprint.rb
1 5
README README.mdown
6 1
...
What I want to do is to match the character strings in filename_list3
to those in names(degree_list)
, and when they are the same, replace the character string in filename_list3
with the integer in degree_list
.
Here is my code:
dput(filename_lists3[1:10])
structure(list(`809` = c("rakelib/blueprint.rb", "projects/daedalus/daedalus.rb"
), `859` = "README", `957` = "spec/debugger/spec_helper.rb",
`1007` = c("README.mdown", "README"), `1038` = "spec/ruby/core/file/stat/setgid_spec.rb",
`1099` = c("vm/test/test_embedding.hpp", "vm/embed.c", "vm/api/embed.h"
), `1179` = c("vm/capi/module.cpp", "kernel/common/module19.rb",
"kernel/common/module18.rb"), `1235` = c("vm/builtin/thread.hpp",
"vm/builtin/thread.cpp", "kernel/common/thread.rb", "kernel/bootstrap/thread.rb"
), `1390` = "spec/ruby/core/marshal/dump_spec.rb", `1422` = c("spec/tags/19/ruby/core/module/constants_tags.txt",
"kernel/common/module19.rb", "kernel/common/module18.rb",
"kernel/common/module.rb")), .Names = c("809", "859", "957",
"1007", "1038", "1099", "1179", "1235", "1390", "1422"))
dput(degree_list[1:10])
structure(c(1, 5, 6, 1, 2, 2, 2, 5, 7, 2), .Names = c("projects/daedalus/daedalus.rb",
"rakelib/blueprint.rb", "README", "README.mdown", "vm/api/embed.h",
"vm/embed.c", "vm/test/test_embedding.hpp", "kernel/common/module18.rb",
"kernel/common/module19.rb", "vm/capi/module.cpp"))
as well as the function and the lapply call:
insert_sna_stat <- function(x, input = degree_list){
for (i in 1:length(x)){
for (n in 1:length(input))
if (names(input)[n] == x[i])
x[i] <- input[n] else
x[i] <- x[i]
}
}
lapply(filename_lists3, insert_sna_stat)
which at this point just generates null. What is going wrong here? How can I modify it to do what I described above?
You can use
rapply
: