R:在没有矢量化的情况下循环数字矢量的元素

时间:2016-07-23 23:35:26

标签: r loops

我正在尝试循环数字向量。我该怎么做呢?通常在for循环中,用for(i in 1:z)开始循环。但是,我想要for(i in vector)之类的东西。例如,请参阅以下内容:

x <- c(839898, 3, 9)
for (i in x) { print(i) }

# Desired output
839898
3
9

在这种情况下,我不想vectorize,因为我正在努力学习如何使用for循环完成此操作。

虽然这篇文章与许多其他文章类似,但在几乎所有其他帖子中我只看到矢量化解决方案,因为有人试图用最少的运行时间完成任务而不是学习循环如何工作

2 个答案:

答案 0 :(得分:2)

我相信你上面打错了,你想要打印i而不是print x。这是RStudio中的执行。

Screenshot of Code Execution in RStudio

答案 1 :(得分:1)

你需要这个:

    <RelativeLayout 
        android:id="@+id/rl1" 
        android:layout_width="match_parent" 
        android:layout_height="wrap_content" 
        android:orientation="vertical" 
        android:paddingTop="10dp" 
        android:paddingRight="10dp">

        <TextView 
            android:id="@+id/tv1" 
            android:layout_width="match_parent" 
            android:layout_height="100dp" 
            android:paddingLeft="12dp" 
            android:text="Setting" 
            android:focusable="true" 
            android:focusableInTouchMode="true" />

        <android.support.design.widget.FloatingActionButton 
            android:id="@+id/fab" 
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content" 
            android:layout_marginLeft="8dp" 
            android:layout_marginRight="8dp" 
            android:src="@drawable/ic_add" 
            app:fabSize="mini" 
            app:pressedTranslationZ="6dp" 
            app:layout_anchorGravity="end|right|center" 
            app:layout_anchor="@id/tv1" />
... a lot of elements here ...
    </RelativeLayout>

您正在直接打印for (i in seq_along(x)) { print(x[i]) } ,这是定义全局环境的。您想在x循环中打印i的{​​{1}}元素