如果为了论证,我想要Python中10长度向量的最后五个元素,我可以在范围索引中使用" - "运算符,这样:
>>> x = range(10)
>>> x
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> x[-5:]
[5, 6, 7, 8, 9]
>>>
Run Code Online (Sandbox Code Playgroud)
R中最好的方法是什么?有没有比我现在的技术更简洁的方法,即使用length()函数?
> x <- 0:9
> x
[1] 0 1 2 3 4 5 6 7 8 9
> x[(length(x) - 4):length(x)]
[1] 5 6 7 8 9
>
Run Code Online (Sandbox Code Playgroud)
这个问题与btw的时间序列分析有关,通常只对最近的数据有用.
这可能是多余的,但我在SO上找不到类似的问题.
是否有一个快捷方式来获取向量或数组中的最后n个元素/条目而不使用计算中向量的长度?
foo <- 1:23
> foo
[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
Run Code Online (Sandbox Code Playgroud)
假设有人想要最后7个实体,我想避免这种繁琐的语法:
> foo[(length(foo)-6):length(foo)]
[1] 17 18 19 20 21 22 23
Run Code Online (Sandbox Code Playgroud)
Python有foo[-7:].R中有类似的东西吗?谢谢!
我有一个婴儿名字的文件,我正在阅读,然后试图得到婴儿名字中的最后一个字符.例如,该文件看起来像..
Name Sex
Anna F
Michael M
David M
Sarah F
Run Code Online (Sandbox Code Playgroud)
我在使用中读到了这个
sourcenames = read.csv("babynames.txt", header=F, sep=",")
Run Code Online (Sandbox Code Playgroud)
我最终希望结果看起来像......
Name Last Initial Sex
Michael l M
Sarah h F
Run Code Online (Sandbox Code Playgroud)
我已设法将名称拆分为单独的字符..
sourceout = strsplit(as.character(sourcenames$Name),'')
Run Code Online (Sandbox Code Playgroud)
但是现在我被困在哪里是如何得到最后一封信,所以在迈克尔的情况下,如何得到'我'.我认为tail()可能会工作,但它会返回最后几条记录,而不是每个Name元素中的最后一个字符.
非常感谢任何帮助或建议.
谢谢 :)
我有矢量 x<-1:5我命名它的元素(错误地)names(x)<-rep(c(letters[1:4], "a")).如何按名称访问最后一个元素?
x["a"]只返回名为的第一个元素"a".